Method for Array Javascript ES6
2 min readApr 17, 2020
Hello Guys,
I want share about method array javascript what different map, filter, find, forEach & Push with easy example to learn.
Example Function Push
Push will add value to end of array
const characters = ["Ninja Ken", "Baby Ben", "Guru Domba"];console.log(characters);// Add the string "Birdie" to the character array with push method
characters.push("Birdie");// Print array characters
console.log(characters);
Example Function ForEach
forEach will loop array and return all value
const characters = ["Ninja Ken", "Baby Ben", "Guru Domba", "Birdie"];// Print all elements in the character array by using the forEach method
characters.forEach((character) => {
console.log(character);
});
Example Function Find
Find will return first result when meet condition
const numbers = [1, 3, 5, 7, 9];// Find multiples of 3 from an array of numbers using the find method
const foundNumber = numbers.find((number) => {
return number % 3 === 0;
});// Print foundNumber
console.log(foundNumber);const characters = [
{id: 1, name: "Ninja Ken", age: 6},
{id: 2, name: "Baby Ben", age: 2},
{id: 3, name: "Guru Domba", age: 100},
{id: 4, name: "Birdie", age: 21}
];// Find an object with id = 3 from constant characters,
const foundCharacter = characters.find((character) => {
return character.id === 3;
});// Print foundCharacter
console.log(foundCharacter);
Example Function Filter
Filter will return all value match condition
const numbers = [1, 2, 3, 4];const evenNumbers = numbers.filter((number) => {
return number % 2 === 0;
});// Print nilai evenNumbers
console.log(evenNumbers);const characters = [
{id: 1, name:"Ninja Ken", age: 14},
{id: 2, name:"Baby Ben", age: 5},
{id: 3, name:"Guru Domba", age: 100}
];const underTwenty = characters.filter((character) => {
return character.age < 20;
});// Print nilai underTwenty
console.log(underTwenty);
Example Function Map
Map will return new array with result operation
const numbers = [1, 2, 3, 4];
const doubledNumbers = numbers.map((number) => {
return number * 2;
});// Print constant doubledNumbers
console.log(doubledNumbers);const names = [
{firstName: "Kate", lastName: "Jones"},
{firstName: "John", lastName: "Smith"},
{firstName: "Dennis", lastName: "Williams"},
{firstName: "David", lastName: "Black"}
];const fullNames = names.map((name) => {
return name.firstName+" "+name.lastName;
});// Print constant fullNames
console.log(fullNames);