useful array method in javascript

useful array method in javascript

We all use arrays in programming languages but do you know javascript provides a lot of inbuilt methods so that we don't have to write nested for loops just to traverse through an array. Let's explore some of the useful methods which make our life easier.

1. some()

some is an array method that returns a boolean value. it will test at least one element from the array satisfied with the given condition. if the test is true then it will stop testing for the rest of the array. if the test condition is false it will search for the remaining elements and it will return false if all the test fails.

example for positive

const arr=[1,2,3,4,5,6,7,8,9]
const result=arr.some(item=>item<9)
console.log(result)

here it will check if the elements inside are less than 9 or not, so it will first check from index 0 i.e "1" since 1 is less than 9 it will stop checking further so it will return true.

example for negative

const arr=[1,2,3,4,5,6,7,8,9]
const result=arr.some(item=>item>9)
console.log(result)

here it will check if the elements inside are greater than 9 or not, so it will first check from index 0 i.e "1" since 1 is less than 9 it will continue checking further so it will return false because none of the elements are greater than 9.

2. every()

every is an array method that returns a boolean value. every method is very similar to some method the difference is it will check every array element pass the test implemented by the given call back function. It will test whether all elements satisfy the condition then only it will return true or else false.

example for positive

const arr=[1,2,3,4,5,6,7,8,9]
const result=arr.every(item=>item<10)
console.log(result)

example for negative

const arr=[1,2,3,4,5,11,7,8,9]
const result=arr.every(item=>item<10)
console.log(result)

3. includes()

includes is an array method that returns a boolean value. it checks whether an array contains a specfic element or not. it is also case-sensitive so be aware whenever testing with strings and characters.

example for stings

const sentence = 'The quick brown fox jumps over the lazy dog.';

const word = 'fox';

console.log(`The word "${word}" ${sentence.includes(word) ? 'is' : 'is not'} in the sentence`);
// expected output: "The word "fox" is in the sentence"

example for arrays

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// expected output: true

console.log(pets.includes('Cat'));
// expected output: false

Note: There are some drawbacks in includes method which we can solve with help of some or find(we'll discuss next) methods.

drawback

includes return true if the value is strictly equal to search element or if it matches the exact reference of object. but here is an example you'll be surprised after seeing this example.

const users=[{name:"khan1",age:33},{name:"khan2",age:44}]
console.log(users.includes({name:"khan1",age:33}))
//expected output:false

the reason is simple it looks for strickly equal, but objects are only strictly equal if they are the same reference. JavaScript does not know an equals method.

takeaway

use includes method if you are dealing with primitive values or else use some or find methods.

4.find()

find method basic functionality is to search the element which satisfies the condition given in callback function. it returns the first element which satisfies the condition or else it will return undefined if the conditions don't satisfy.

example

const users=[{name:"khan1",age:33},{name:"khan1",age:35},{name:"khan2",age:44}]
console.log(users.find(item=>item.name=="khan1"))
//expected output:{name:"khan1",age:33}

5.findIndex()

findIndex method basic functionality is to search the element which satisfies the condition given in callback function and return its index value. just like find()it returns the first element index which satisfies the condition or else it will return -1 if the conditions don't satisfy.

example

const users=[{name:"khan1",age:33},{name:"khan2",age:35},{name:"khan2",age:44}]
console.log(users.findIndex(item=>item.name=="khan2"))
//expected output:1

The important part is that findIndex won't return all indices of users with that name.

6.reverse()

as the name says this will reverse the array.

example

const arr=[1,2,3,4,5,6,7,8,9]
console.log(arr.reverse())
//expected output:[ 9, 8, 7, 6, 5, 4, 3, 2, 1 ]

7.map()

This is one of the most popularly used method in javascript. whenever you want to transform all the values in an array then you should use map(). it returns an new array with the results of the callback function condition to all the elements. if this sounds confusing let's look at this example1.

example1

const arr=[1,2,3,4,5,6,7,8,9]
const newArr=arr.map(element=>element+1)
console.log(newArr)
//expected output:[ 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

Note: since it return new array it does not mutate original array.

What if you want to change the specific element in an array??

there are many ways to do this but with help of map you can get newly updated array.

const users=[{name:"khan1",age:33},{name:"khan2",age:35},{name:"khan3",age:44}]
const newUsers=users.map(element=>{
  if(element.name=="khan2"){
    return {...element,age:45}
  }
  return element
})
console.log(newUser)
//expected output:[ { name: 'khan1', age: 33 },{ name: 'khan2', age: 45 },{ name: 'khan3', age: 44 } ]

8.forEach()

forEach loops through every element and executes its callback function to every array elements.

How forEach() is different from map() ??

  • forEach doesn't return a new array.
  • forEach can mutate original array but this is not way to use forEach.
const array = [1, 2, 3, 4, 5]
array.forEach((item) => console.log(item+1))
//expected output:
//2
//3
//4
//5
//6

9.filter()

As the name says it filters our array and returns a new filtered array. It will loop through all the elements and test with our callback function and returns an array of elements that satisfy the test.

example

const users=[{name:"john",age:33,gender:"male"},{name:"emma",age:35,gender:"girl"},{name:"mark",age:44,gender:"male"}]
const filteredArray=users.filter(item=>item.gender=="male")
console.log(filteredArray)
//expected output:[ { name: 'john', age: 33, gender: 'male' },{ name: 'mark', age: 44, gender: 'male' } ]

10.sort()

As the name says it will sort the array. If we don't provide any comparison function then the default sort type is ascending based on converting the elements into strings and then comparing them according to UTF-16 code unit values.

For example: "banana" comes after "Bat", 70 comes after 8 but if the numbers are converted to strings then "70" comes before "8".

syntax

// Functionless
sort()

// Arrow function
sort((a, b) => { /* ... */ } )

// Compare function
sort(compareFunction)

// Inline compare function
sort(function compareFunction(a, b) { /* ... */ })

let's take a good example to showcase the sort method.

const items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic', value: 13 },
  { name: 'Zeros', value: 37 }
];

// sort by value
const valueSort=[...items].sort(function (a, b) {
  return a.value - b.value;
});
console.log(valueSort)
//expected output:[ { name: 'The', value: -12 }, { name: 'Magnetic', value: 13 }, { name: 'Edward', value: 21 }, { name: 'Sharpe', value: 37 }, { name: 'Zeros', value: 37 },  { name: 'And', value: 45 } ]

// sort by name
const nameSort=[...items].sort(function(a, b) {
  const nameA=a.name.toUpperCase();
  const nameB=b.name.toUpperCase();
  if ( nameA< nameB) {
    return -1;
  }
  if (nameA > nameB) {
    return 1;
  }
  // names must be equal
  return 0;
})
console.log(nameSort)
//expected output:[ { name: 'And', value: 45 }, { name: 'Edward', value: 21 }, { name: 'Magnetic', value: 13 },  { name: 'Sharpe', value: 37 }, { name: 'The', value: -12 }, { name: 'Zeros', value: 37 } ]

11.reduce()

This is one of the most powerful methods introduced in javascript. If we want to talk about its use cases then we should write another blog just for its use cases, but still we look into the overview of reduce method.

The reduce method will run the callback function on every element of an array and the result(return) of the callback function will get assigned to previousValue. the final return of running reduce function will be a single value.

syntax

the reduce method will have 2 parameters where 1 is optional.

1) callback function which will run on every element of an array.

A callback function have 4 arguments previousValue(accumulator), currentValue(current), index, array.

  • prviousValue(accumulator) is the value of result from the previous callback function. But on the first call, this value will be initial value, If the initial value is not specified then this will be the value of array[0].
  • currentValue is the value of the current element. But on the first call, this will be the value of array[0] if the initial value is specified, otherwise it will be an array[1].
  • index is the index position of the current element. But on the first call, this will be index 0 if the initial value is specified, otherwise it will be 1.
  • An array to traverse.

2) initial value is the value that is assigned to previousValue on the first call of callback function. If it is not specified then the previousValue will get initialized with array[0] value, Also current value will be array[1] and index will be 1.

// Arrow function
reduce((previousValue, currentValue) => { /* ... */ } )
reduce((previousValue, currentValue, currentIndex) => { /* ... */ } )
reduce((previousValue, currentValue, currentIndex, array) => { /* ... */ } )
reduce((previousValue, currentValue, currentIndex, array) => { /* ... */ }, initialValue)

// Callback function
reduce(callbackFn)
reduce(callbackFn, initialValue)

// Inline callback function
reduce(function(previousValue, currentValue) { /* ... */ })
reduce(function(previousValue, currentValue, currentIndex) { /* ... */ })
reduce(function(previousValue, currentValue, currentIndex, array) { /* ... */ })
reduce(function(previousValue, currentValue, currentIndex, array) { /* ... */ }, initialValue)

since there are so many use cases we will look into a simple example.

example(sum of array elements):

const arr=[1,2,3,4,5,6,7,8,9]
const sum=arr.reduce((previousValue,currentValue)=>previousValue+currentValue,0)
console.log(sum)
//expected output:45

Notice here we are specifying the initial value to 0. So previousValue will be 0, currentValue will be arr[1].

There are some edge cases in reduce method it will be good to know.click here for the edge cases.

That's it folks

Now that you know more than 10 methods that are very popular and easy to use. I recommend you read more about other methods which might be helpful too. To know more click here.