DEV Community

Cover image for Array Operations in JavaScript
Rahul Raj
Rahul Raj

Posted on • Edited on

Array Operations in JavaScript

Array :

  • An Array is a linear data structure used to store multiple values, accessed using zero-based indexing.

  • It is used to store multiple values in a single variable.

  • Arrays can store different data types value (number, string, boolean , object, etc.).

  • Arrays are represented using square brackets [].

  • Each value inside an array is called an element.

  • Every array has a property called length. It returns the total number of elements in array .

  • Arrays are mutable, means we can change the length of array as well as modify the value of array .

Array Operations :

1 . push()

  • if we want to add one or more elements to the end of an array then we need to use push() .
  • it modify the existing original array not return new Array
  • it returns the new array length .
  • pros : operations are simple & fast .
  • cons : change the original array .
let arr = [1, 2, 3];

let returnedValue = arr.push(4);

console.log(arr);           
console.log(returnedValue); 

Enter fullscreen mode Exit fullscreen mode

Output

[1, 2, 3, 4]
 4
Enter fullscreen mode Exit fullscreen mode

2 . pop()

  • if we want to remove/delete only last element from the array then we need to use pop().
  • It also modify the original array .
  • It returns the deleted element .
  • pros : easy to use
  • cons : change the original array .
let arr = [10, 20, 30];

let returnedValue = arr.pop();

console.log(arr);          
console.log(returnedValue); 

Enter fullscreen mode Exit fullscreen mode

Output

[ 10, 20 ]
30
Enter fullscreen mode Exit fullscreen mode

3 . unshift()

  • if we want to add one or more elements at starting then we need to use unshift().
  • it modify the original array .
  • It returns the new array length .
let arr = [2, 3];

let returnedValue = arr.unshift(0,1);

console.log(arr);          
console.log(returnedValue);
Enter fullscreen mode Exit fullscreen mode

Output

[ 0, 1, 2, 3 ]
4
Enter fullscreen mode Exit fullscreen mode

4 . shift()

  • if we want to remove/delete only first element of array then we need to use shift().
  • it modifies the original array .
  • It returns the deleted element .
let arr = [1, 2, 3];

let returnedValue = arr.shift();

console.log(arr);          
console.log(returnedValue); 
Enter fullscreen mode Exit fullscreen mode

Output

[ 2, 3 ]
1
Enter fullscreen mode Exit fullscreen mode

5 . splice()

  • if we want to add / delete / replace one or more element(s) at specific index , then we need to use splice().
  • It modifies the original Array.
  • It returns the array of removed elements . if we will not delete any element from the array then it returns empty array . -Syntax :
    • arr.splice(start,deleteCount, item1, item2, …);
let arr = [1, 2, 3];
let result = arr.splice(1, 1, 10, 20); // add 10,20 at index 1, remove 0 elements

console.log(result); 
console.log(arr);  
Enter fullscreen mode Exit fullscreen mode

Output

[ 2 ]
[ 1, 10, 20, 3 ]
Enter fullscreen mode Exit fullscreen mode

Note :

  • splice(start) : Removes everything from start to end & return -> Array of removed elements .
  • splice(start, 0) : Removes 0 elements → add nothing & return -> [] empty array .
  • splice(start, deleteCount) : Removes deleteCount elements from start & return -> Array of removed elements .
  • splice(start, deleteCount, item1, item2, …) : Remove deleteCount elements from start and insert new items & return -> Array of removed elements

6 . map()

  • If we want to make a new array from an existing array based on some condition or change, we use map().
  • The new array will always have the same number of elements as the original array.
  • Original array does not change .
  • map() returns new array of same length.
let nums = [1, 2, 3];

let returnedValue = nums.map(n => n * 2);

console.log(nums);         
console.log(returnedValue); 
Enter fullscreen mode Exit fullscreen mode

Output

[ 1, 2, 3 ]
[ 2, 4, 6 ]

Enter fullscreen mode Exit fullscreen mode
let nums = [1, 2, 3, 4, 5];

let newNums = nums.map(n => {
  if (n % 2 === 0) {
    return n * 2;   
  } else {
    return n;      
  }
});

console.log(nums);   
console.log(newNums); 
Enter fullscreen mode Exit fullscreen mode

Output

[ 1, 2, 3, 4, 5 ]
[ 1, 4, 3, 8, 5 ]
Enter fullscreen mode Exit fullscreen mode
let nums = [1, 2, 3, 4, 5];

let newNums = nums.map(n => {
  if (n % 2 === 0) return n * 2;
  else if (n === 3) return 99;
  else return n;
});

console.log(newNums); 
Enter fullscreen mode Exit fullscreen mode

Output

[ 1, 4, 99, 8, 5 ]
Enter fullscreen mode Exit fullscreen mode

7 . filter()

  • if we want to create an array based on some match condition from existing array then we need to use filter().
  • here , existing array does not change .
  • filter() return new array based on match condition .
  • Length of new array ≤ original array.
let nums = [10, 15, 20];

let returnedValue = nums.filter(n => n > 10);

console.log(nums);         
console.log(returnedValue); 
Enter fullscreen mode Exit fullscreen mode

Output

[ 10, 15, 20 ]
[ 15, 20 ]
Enter fullscreen mode Exit fullscreen mode
let nums = [5, 10, 15, 20, 25, 30];

let filtered = nums.filter(n => {
  if (n % 2 === 0 && n > 10) {

    return true;
  } else if (n === 5 || n === 15) {

    return true;
  } else {

    return false;
  }
});

console.log(filtered); 
console.log(nums);  
Enter fullscreen mode Exit fullscreen mode

Output

[ 5, 15, 20, 30 ]
[ 5, 10, 15, 20, 25, 30 ]
Enter fullscreen mode Exit fullscreen mode
let nums = [5, 10, 15, 20, 25, 30];

let filtered = nums.filter(n => (n % 2 === 0 && n > 10) || n === 5);
// even numbers greater than 10 OR number equal to 5

console.log(filtered); 
Enter fullscreen mode Exit fullscreen mode

Output

[ 5, 20, 30 ]
Enter fullscreen mode Exit fullscreen mode

8 reduce()

  • If we want to perform a sum operation on all elements of a given array and convert them into a single value, then we use the reduce() method.
  • Reduces the array to a single value.
  • Return -> Single value
  • reduce() does not modify the original array.
  • It only reads elements and returns a single value.
let nums = [10, 20, 30];

let sum = nums.reduce((total, n) => total + n, 0);

console.log(sum);  
console.log(nums); 

Enter fullscreen mode Exit fullscreen mode

Output

60
[ 10, 20, 30 ]
Enter fullscreen mode Exit fullscreen mode

note : total(here) -> Something that collects or gathers values step by step OR An accumulator is a variable(total) that stores the running total or combined result .

9. includes()

-If we want to check whether a particular element is present in a given array or not, we use includes().

  • Returns boolean → true or false
  • Does not change the original array.
let arr = ["JS", "Java"];

let returnedValue = arr.includes("JS");

console.log(arr);          
console.log(returnedValue); 

Enter fullscreen mode Exit fullscreen mode

Output

[ 'JS', 'Java' ]
true
Enter fullscreen mode Exit fullscreen mode

10. find()

  • It is used to return the first element that matches the given condition.
  • When only one result is required.
  • return either Single value or undefined.
  • Does not change the original array.
let nums = [5, 12, 8];

let returnedValue = nums.find(n => n > 10);

console.log(nums);        
console.log(returnedValue);

Enter fullscreen mode Exit fullscreen mode

Output

[ 5, 12, 8 ]
12
Enter fullscreen mode Exit fullscreen mode

Note :

Non-mutating methods → map(), filter(), reduce(), find(), includes()

Mutating methods → push(), pop(), shift(), unshift(), splice(), sort()

Image

Top comments (0)