Frequently used array methods in JavaScript

1) concat concat method will merge arrays and return a new array. example

const arr1 = [1,2,3]
const arr2 = [a,b,c]
const ans = arr1.concat(arr2)
console.log(ans) // [1,2,3,a,b,c]
  • concat will return a shallow copy of an existing array
  • concat can take multiple values as parameters.
    const arr1 = [1,2,3]
    const arr2 = [a,b,c]
    const arr3 = [x.y,z]
    const ans = arr1.concat(arr2,arr3)
    console.log(ans) // [1,2,3,a,b,c,x,y,z]
    

2) find find will return the first element from the array which satisfy the condition.

const arr = [1,2,3,4,5]
const ans = arr.find(number => number%2 === 0)
console.log(ans) // 2
  • if the condition does not match then find will return undefine
  • The find method executes the callback function until it satisfies the condition and will return the value on the first successful match. find with object
const obj = [
    {name: "elon", company: "Tesla"},
    {name:"bill", company:"Microsoft"},
    {name:"jobs", company:"Apple"},
]
console.log(obj.find(()=>{name === "elon"}) //{name: "elon", company: "Tesla"}

3) some some will check at least one element satisfies the condition then return true otherwise return false

const arr = ['apple', 'orange', 'mango', 'banana']
console.log(arr.some(word => word.length >= 4)) // true
console.log(arr.some(wod => word.length >= 8)) // false
  • if the condition does not match then some will return undefine
  • Some method executes the callback function until it satisfies the condition and will return the true on the first successful match.

4) map map will create a new array populated with the results of calling a provided function on every element in the calling array.

const arr = [10,20,30,40,50]
const ans = arr.map(number => number+5)
console.log(ans) // [15,25,35,45,55]
  • map will return a new array
  • map is a pure function
const obj = [
    {name: "elon", company: "Tesla"},
    {name:"bill", company:"Microsoft"},
    {name:"jobs", company:"Apple"},
]
const ans = obj.map(({name, company}) => ({[name]:company})
console.log(ans) // [{"elon" : "Tesla"}, {"bill":"Microsoft"},{"jobs":"Apple"}]

5) filter filter will create a new array with all elements which satisfies the conditions

const arr = ['apple', 'orange', 'mango', 'banana']
const  ans = arr.filter(word => word.length === 5)
console.log(ans) //  ['apple','mango']
const ans1 = arr.filter(word => word.length > 4)
console.log(ans1) // ['apple', 'orange', 'mango', 'banana']
  • filter will return a new array
  • filter is a pure function