DEV Community

Jenil
Jenil

Posted on

10 JavaScript Array Methods Every Developer Should Master (Part 1)

"With great power comes great responsibility."
— Uncle Ben, Spider-Man (2002)

Just like Spider-Man had to master his newfound powers, developers need to master the powerful arrays methods of JavaScript to code efficiently and responsibly.

Let’s dive into some of these must-know array methods!

1. find

The find() method returns the value of the first array element that satisfies the provided test function.

arr.find(callback(element, index, arr),thisArg)

  • Returns the value of the first element in the array that satisfies the given function.
  • Returns undefined if none of the elements satisfy the function
const cuties = [
  { name: "Wanda Maximoff", age: 31 },
  { name: "Natasha Romanoff", age: 32 },
  { name: "Jane Foster", age: 27 },
  { name: "Gwen Stacy", age: 26 },
];

// find method returns the value of the first element 
// in the array that satisfies the given function 
// or else returns undefined
let cuty = cuties.find(({ age }) => age >= 30);

// Output: { name: 'Wanda Maximoff', age: 31 }
console.log(cuty);
Enter fullscreen mode Exit fullscreen mode

2. findIndex

The findIndex() method returns the index of the first array element that satisfies the provided test function or else returns -1.

arr.findIndex(callback(element, index, arr),thisArg)

  • Returns the index of the first element in the array that satisfies the given function.
  • Returns -1 if none of the elements satisfy the function.
const cuties = [
  { name: "Wanda Maximoff", age: 31 },
  { name: "Natasha Romanoff", age: 32 },
  { name: "Jane Foster", age: 27 },
  { name: "Gwen Stacy", age: 26 },
];

// findIndex method returns the index of the first array element 
// that satisfies the provided test function or else returns -1.
let cutyIndex = cuties.findIndex(({ age }) => age >= 30);

// Output: 0
console.log(cutyIndex);
Enter fullscreen mode Exit fullscreen mode

3. indexOf

The indexOf() method returns the first index of occurance of an array element, or -1 if it is not found.

arr.indexOf(searchElement, fromIndex)

  • Returns the first index of the element in the array if it is present at least once.
  • Returns -1 if the element is not found in the array.
const productPrices = [5, 12, 3, 20, 5, 2, 50];

// indexOf() returns the first index of occurance 
// of an array element, or -1 if it is not found.
let firstIndex = productPrices.indexOf(20);
console.log(firstIndex); // 3

let secondIndex = productPrices.indexOf(5);
console.log(secondIndex); // 0

// The second argument specifies the search start index
let thirdIndex = productPrices.indexOf(5, 1);
console.log(thirdIndex); // 4

// indexOf returns -1 if not found
let notFoundIndex = productPrices.indexOf(15);
console.log(notFoundIndex); // -1
Enter fullscreen mode Exit fullscreen mode

4. sort

The sort() method sorts the items of an array in a specific order (ascending or descending).

arr.sort(compareFunction)

  • Returns the array after sorting the elements of the array in place (meaning that it changes the original array and no copy is made).
const avengers = ["Captain", "Tony", "Thor", 
                  "Natasha", "Bruce", "Clint"];

// modifies the array in place
avengers.sort(); 

// [ 'Bruce', 'Captain', 'Clint', 'Natasha', 'Thor', 'Tony' ]
console.log(avengers);  

const nums = [1000, 50, 2, 7, 14];

// number is converted to string and sorted
nums.sort(); 

// Output: [ 1000, 14, 2, 50, 7 ]
console.log(nums) 

// sort nums in ascending order by providing compare function
nums.sort((a, b) => a - b);

// Output: [ 2, 7, 14, 50, 1000 ]
console.log(nums);
Enter fullscreen mode Exit fullscreen mode

5. includes

The includes() method checks if an array contains a specified element or not.

arr.includes(valueToFind, fromIndex)

The includes() method returns:

  • true if  is found anywhere within the array searchValue
  • false if  is not found anywhere within the array searchValue
const avengers = ["Captain", "Tony", "Thor", 
                 "Natasha", "Bruce", "Clint"];

// includes() method returns true if an array contains 
// a specified element or else returns false.
let check1 = avengers.includes("Thor");
console.log(check1); // true 

// second argument specifies position to start the search
let check2 = avengers.includes("Thor", 3);
console.log(check2); // false

// The search starts from the 4th-to-last element ("Hulk") 
// and checks the rest of the array for "Thor". 
let check3 = avengers.includes("Thor", -4);
console.log(check3); // true
Enter fullscreen mode Exit fullscreen mode

6. forEach

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

arr.forEach(callback(currentValue), thisArg)

forEach() does not execute callback for array elements without values.

• Returns undefined.

const nums = [120, 150, 80, , 200];

// forEach() method executes a provided 
// function for each array element which 
// have values. It returns undefined.

/*
num 0: 120
num 1: 150
num 2: 80
num 4: 200
*/
nums.forEach((value, index) => {
    console.log('num ' + index + ': ' + value);
});
Enter fullscreen mode Exit fullscreen mode

7. slice

The slice() method returns a shallow copy of a portion of an array into a new array object.

arr.slice(start, end)

• Returns a new array containing the extracted elements.

const fruits = ["Apple", "Banana", "Orange", "Grape", "Mango"];

// slicing the array (from start to end)
let slicedFruits1 = fruits.slice();
console.log(slicedFruits1); // [ 'Apple', 'Banana', 'Orange', 'Grape', 'Mango' ]

// slicing from the third element
let slicedFruits2 = fruits.slice(2);
console.log(slicedFruits2); // [ 'Orange', 'Grape', 'Mango' ]

// slicing from the second element to fourth element
let slicedFruits3 = fruits.slice(1, 4);
console.log(slicedFruits3); // [ 'Banana', 'Orange', 'Grape' ]

// slicing the array from start to second-to-last
let slicedFruits4 = fruits.slice(0, -1);
console.log(slicedFruits4); // [ 'Apple', 'Banana', 'Orange', 'Grape' ]

// slicing the array from third-to-last
let slicedFruits5 = fruits.slice(-3);
console.log(slicedFruits5); // [ 'Orange', 'Grape', 'Mango' ]
Enter fullscreen mode Exit fullscreen mode

8. splice

The splice() method modifies an array (adds, removes or replaces elements).

arr.splice(start, deleteCount, item1, ..., itemN)

• Returns an array containing the deleted elements.

let animals = ["Dog", "Cat", "Elephant", "Lion"];

// replacing "Elephant" & "Lion" with "Tiger" & "Giraffe"
let removedAnimals1 = animals.splice(2, 2, "Tiger", "Giraffe");
console.log(removedAnimals1); // [ 'Elephant', 'Lion' ]
console.log(animals); // [ 'Dog', 'Cat', 'Tiger', 'Giraffe' ]

// adding elements without deleting existing elements
let removedAnimals2 = animals.splice(1, 0, "Elephant", "Lion");
console.log(removedAnimals2); // []
console.log(animals); // [ 'Dog', 'Elephant', 'Lion', 'Cat', 'Tiger', 'Giraffe' ]

// removing 3 elements
let removedAnimals3 = animals.splice(2, 3);
console.log(removedAnimals3); // [ 'Lion', 'Cat', 'Tiger' ]
console.log(animals); // [ 'Dog', 'Elephant', 'Giraffe' ]
Enter fullscreen mode Exit fullscreen mode

9. every

The every() method checks if all the array elements pass the given test function.

arr.every(callback(currentValue), thisArg)

The every() method returns:

  • true - if all the array elements pass the given test function (callback returns a truthy value).
  • false - if any array element fails the given test function.
const nums1 = [ 1 , 2 , 3 , 4 , 5];

// every() method returns true if all the array 
// elements pass the given test function or else
// returns false
let result1 = nums1.every(element => element < 6);

// Output: true
console.log(result1); 

const nums2 = [ 1 , 2 , 7 , 4 , 5];
let result2 = nums2.every(element => element < 6);

// Output: false
console.log(result2);
Enter fullscreen mode Exit fullscreen mode

10. some

The some() method tests whether any of the array elements pass the given test function.

arr.some(callback(currentValue), thisArg)

  • Returns true if an array element passes the given test function (callback returns a truthy value).
  • Otherwise, it returns false
const nums1 = [ 8 , 2 , 7 , 9 , 6];

// some() method returns true if any of the array 
// elements pass the given test function or else 
// returns false
let result1 = nums1.some(element => element < 6);

// Output: true
console.log(result1); 

const nums2 = [ 8 , 6 , 7 , 9 , 10];
let result2 = nums2.some(element => element < 6);

// Output: false
console.log(result2);
Enter fullscreen mode Exit fullscreen mode

Stay tuned for Part 2 of our series, where we'll dive into even more essential JavaScript array methods! Happy Leanring!

Top comments (0)