JavaScript Array

forEach

The forEach() method executes a provided function once for each array element.

usage:

forEach(() => {...}) forEach((value) => {...}) forEach((value,key) => {...}) forEach((value,key,array) => {...})

example:

const arrayExample = ['a','b','c','d'] //forEach((value) => {...}) arrayExample.forEach((e)=>{ console.log(e); }) //output: 'a' //output: 'b' //output: 'c' //output: 'd' //forEach((value,key) => {...}) arrayExample.forEach((e,i)=>{ console.log(e,i); }) //output: 'a' 0 //output: 'b' 1 //output: 'c' 2 //output: 'd' 3 //forEach((value,key,array) => {...}) arrayExample.forEach((e,i,arr)=>{ console.log(e,i,arr); }) //output: 'a' 0 ['a','b','c','d'] //output: 'b' 1 ['a','b','c','d'] //output: 'c' 2 ['a','b','c','d'] //output: 'd' 3 ['a','b','c','d']

map

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

usage:

map(() => {...}) map((element) => {...}) map((element,key) => {...}) map((element,key,array) => {...})

example:

const arrayExample = ['a','b','c','d'] //map((value) => {...}) const arrayMap = arrayExample.map((x)=>(`Get: ${x}`)); console.log(arrayMap) //output: [ 'Get: a', 'Get: b', 'Get: c', 'Get: d' ] //const arrayMap = map((value,key) => {...}) const arrayMap = arrayExample.map((x,i)=>(`Index ${i}: ${x}`)); console.log(arrayMap) //output: [ 'Index 0: a', 'Index 1: b', 'Index 2: c', 'Index 3: d' ] //const arrayMap = map((value,key,array) => {...}) const arrayMap = arrayExample.map((x,i,arr)=>(`Index ${i}: ${x} by ${arr}`)); console.log(arrayMap) /*output: [ 'Index 0: a by a,b,c,d', 'Index 1: b by a,b,c,d', 'Index 2: c by a,b,c,d', 'Index 3: d by a,b,c,d' ]*/

filter

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

usage:

filter((element) => {...}) filter((element,key) => {...}) filter((element,key,array) => {...})

example:

const arrayExample = ['apple','banana','coconut','grape','grapefruit'] //filter((element) => {...}) const arrayFilter = arrayExample.filter((x)=>(x.length > 5)); console.log(arrayFilter) //output: [ 'banana', 'coconut', 'grapefruit' ] //filter((element,key) => {...}) const arrayFilter = arrayExample.filter((x,i)=>(i%2==0)); console.log(arrayFilter) //output: [ 'apple', 'coconut', 'grapefruit' ]

Reference:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

tags: javascript