Javascript map() function

khafidprayoga

Khafid Prayoga

Posted on January 26, 2022

Javascript map() function

Map merupakan sebuah fungsi yang dapat anda gunakan pada Javascript untuk membuat array baru melalui kondisi tertentu dengan inputan data yang berasal dari array yang akan dimanipulasi, kode akan terlihat lebih clean daripada menggunakan for-loop.

Berikut contoh kode yang buruk

const students = ["Bob", "Alice", "Robert"];
const greetStudents = [];

for (let i = 0; i < students.length; i++) {
  greetStudents.push(`Hello, ${students[i]}!`);
}

console.log(greetStudents);
Enter fullscreen mode Exit fullscreen mode

Output:
[ 'Hello, Bob!', 'Hello, Alice!', 'Hello, Robert!' ]

Berikut contoh kode yang clean

const students = ["Bob", "Alice", "Robert"];
const greetStudents = students.map((student) => `Hello, ${student}!`);

console.log(greetStudents);
Enter fullscreen mode Exit fullscreen mode

Output:
[ 'Hello, Bob!', 'Hello, Alice!', 'Hello, Robert!' ]

Contoh kode yang lain jika mengunakan lodash

const _ = require("lodash");

const students = ["Bob", "Alice", "Robert"];
const greet = (student) => `Hello, ${student}!`;
const greetStudents = _.map(students, greet);

console.log(greetStudents);
Enter fullscreen mode Exit fullscreen mode

Output:
[ 'Hello, Bob!', 'Hello, Alice!', 'Hello, Robert!' ]

Terlihat apabila anda menggunakan lodash, kode akan lebih mudah dibaca dan lebih terstruktur, karena bisa menghemat baris kode, agar tidak terlau panjang.

Referensi:
Lodash - map

💖 💪 🙅 🚩
khafidprayoga
Khafid Prayoga

Posted on January 26, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Javascript IIFE
javascript Javascript IIFE

January 30, 2022

Javascript filter() function
javascript Javascript filter() function

January 28, 2022

Javascript map() function
javascript Javascript map() function

January 26, 2022