DEV Community

Cover image for Array Mutating & Non-Mutating Methods
MD ASHRAF
MD ASHRAF

Posted on

Array Mutating & Non-Mutating Methods

Lets first see the list of function categorised as Mutating Methods & Non-Mutating Methods below, will then share example of each function:

+-----------------------+---------------------------+
| Mutating Methods      | Non-Mutating Methods      |
+-----------------------+---------------------------+
| push()                | concat()                  |
| pop()                 | slice()                   |
| shift()               | map()                     |
| unshift()             | filter()                  |
| splice()              | reduce()                  |
| sort()                | reduceRight()             |
| reverse()             | forEach()                 |
| fill()                | every()                   |
| copyWithin()          | some()                    |
|                       | find()                    |
|                       | findIndex()               |
|                       | findLast() (ES2023)       |
|                       | findLastIndex() (ES2023)  |
|                       | includes()                |
|                       | indexOf()                 |
|                       | lastIndexOf()             |
|                       | join()                    |
|                       | toString()                |
|                       | toLocaleString()          |
|                       | flat()                    |
|                       | flatMap()                 |
|                       | at() (ES2022)             |
|                       | toReversed() (ES2023)     |
|                       | toSorted() (ES2023)       |
|                       | toSpliced() (ES2023)      |
|                       | with() (ES2023)           |
|                       | Array.from()              |
|                       | Array.isArray()           |
|                       | Array.of()                |
|                       | Object.groupBy() (ES2024) |
|                       | Map.groupBy() (ES2024)    |
+-----------------------+---------------------------+
Enter fullscreen mode Exit fullscreen mode

Array Methods that Mutate the Original Array:

push(): Adds one or more elements to the end of an array and returns the new length of the array.

let arr = [1, 2, 3];
arr.push(4); // arr is now [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

pop(): Removes the last element from an array and returns that element.

let arr = [1, 2, 3];
let removed = arr.pop(); // removed is 3, arr is now [1, 2]
Enter fullscreen mode Exit fullscreen mode

shift(): Removes the first element from an array and returns that element.

let arr = [1, 2, 3];
let removed = arr.shift(); // removed is 1, arr is now [2, 3]
Enter fullscreen mode Exit fullscreen mode

unshift(): Adds one or more elements to the beginning of an array and returns the new length of the array.

let arr = [1, 2, 3];
arr.unshift(0); // arr is now [0, 1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

splice(): Adds, removes, or replaces elements in an array at a specified index, and returns an array containing the deleted elements.

let arr = [1, 2, 3, 4, 5];
let removed = arr.splice(2, 1, 6, 7); // removed is [3], arr is now [1, 2, 6, 7, 4, 5]

Enter fullscreen mode Exit fullscreen mode

sort(): Sorts the elements of an array in place and returns the reference to the same array, now sorted.

let arr = [3, 1, 4, 1, 5];
arr.sort(); // arr is now [1, 1, 3, 4, 5] (default string sort, or with a compare function)

Enter fullscreen mode Exit fullscreen mode

reverse(): Reverses the order of the elements in an array in place and returns the reference to the same array.

let arr = [1, 2, 3];
arr.reverse(); // arr is now [3, 2, 1]
Enter fullscreen mode Exit fullscreen mode

fill(): Fills all the elements of an array from a start index to an end index with a static value.

let arr = [1, 2, 3, 4, 5];
arr.fill(0, 2, 4); // arr is now [1, 2, 0, 0, 5]

Enter fullscreen mode Exit fullscreen mode

copyWithin(): Copies part of an array to another location in the same array and returns the modified array.

let arr = [1, 2, 3, 4, 5];
arr.copyWithin(0, 3); // arr is now [4, 5, 3, 4, 5]

Enter fullscreen mode Exit fullscreen mode

Array Methods that Do Not Mutate the Original Array

These methods return a new array or a new value, leaving the original array unchanged.

concat(): Joins two or more arrays and returns a new array.


let arr1 = [1, 2];
let arr2 = [3, 4];
let newArr = arr1.concat(arr2); // newArr is [1, 2, 3, 4], arr1 and arr2 are unchanged
Enter fullscreen mode Exit fullscreen mode

slice(): Returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included).

let arr = [1, 2, 3, 4, 5];
let newArr = arr.slice(1, 4); // newArr is [2, 3, 4], arr is unchanged

Enter fullscreen mode Exit fullscreen mode

map(): Creates a new array populated with the results of calling a provided function on every element in the calling array.

let arr = [1, 2, 3];
let newArr = arr.map(x => x * 2); // newArr is [2, 4, 6], arr is unchanged

Enter fullscreen mode Exit fullscreen mode

filter(): Creates a new array with all elements that pass the test implemented by the provided function.

let arr = [1, 2, 3, 4, 5];
let newArr = arr.filter(x => x % 2 === 0); // newArr is [2, 4], arr is unchanged

Enter fullscreen mode Exit fullscreen mode

reduce(): Executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

let arr = [1, 2, 3];
let sum = arr.reduce((acc, current) => acc + current, 0); // sum is 6, arr is unchanged

Enter fullscreen mode Exit fullscreen mode

reduceRight(): Similar to reduce(), but executes the reducer function from right to left.

let arr = [1, 2, 3];
let sum = arr.reduceRight((acc, current) => acc + current, 0); // sum is 6, arr is unchanged

Enter fullscreen mode Exit fullscreen mode

forEach(): Executes a provided function once for each array element. (Returns undefined, does not create a new array).

let arr = [1, 2, 3];
arr.forEach(x => console.log(x)); // arr is unchanged

Enter fullscreen mode Exit fullscreen mode

every(): Tests whether all elements in the array pass the test implemented by the provided function. Returns a Boolean value.

let arr = [1, 2, 3];
let allEven = arr.every(x => x % 2 === 0); // allEven is false, arr is unchanged

Enter fullscreen mode Exit fullscreen mode

some(): Tests whether at least one element in the array passes the test implemented by the provided function. Returns a Boolean value.

let arr = [1, 2, 3];
let hasEven = arr.some(x => x % 2 === 0); // hasEven is true, arr is unchanged

Enter fullscreen mode Exit fullscreen mode

find(): Returns the value of the first element in the provided array that satisfies the provided testing function. Otherwise, undefined is returned.

let arr = [1, 2, 3, 4, 5];
let found = arr.find(x => x > 3); // found is 4, arr is unchanged

Enter fullscreen mode Exit fullscreen mode

findIndex(): Returns the index of the first element in the array that satisfies the provided testing function. Otherwise, -1 is returned.

let arr = [1, 2, 3, 4, 5];
let index = arr.findIndex(x => x > 3); // index is 3, arr is unchanged

Enter fullscreen mode Exit fullscreen mode

findLast() (ES2023): Returns the value of the last element in the array that satisfies the provided testing function. Otherwise, undefined is returned.

let arr = [1, 2, 3, 4, 3];
let found = arr.findLast(x => x === 3); // found is 3, arr is unchanged

Enter fullscreen mode Exit fullscreen mode

findLastIndex() (ES2023): Returns the index of the last element in the array that satisfies the provided testing function. Otherwise, -1 is returned.

let arr = [1, 2, 3, 4, 3];
let index = arr.findLastIndex(x => x === 3); // index is 4, arr is unchanged

Enter fullscreen mode Exit fullscreen mode

includes(): Determines whether an array includes a certain value among its entries, returning true or false as appropriate.

let arr = [1, 2, 3];
let hasTwo = arr.includes(2); // hasTwo is true, arr is unchanged

Enter fullscreen mode Exit fullscreen mode

indexOf(): Returns the first index at which a given element can be found in the array, or -1 if it is not present.

let arr = [1, 2, 3];
let index = arr.indexOf(2); // index is 1, arr is unchanged

Enter fullscreen mode Exit fullscreen mode

lastIndexOf(): Returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex.

let arr = [1, 2, 3, 2];
let index = arr.lastIndexOf(2); // index is 3, arr is unchanged

Enter fullscreen mode Exit fullscreen mode

join(): Creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string.

let arr = [1, 2, 3];
let str = arr.join('-'); // str is "1-2-3", arr is unchanged

Enter fullscreen mode Exit fullscreen mode

toString(): Returns a string representing the specified array and its elements.

let arr = [1, 2, 3];
let str = arr.toString(); // str is "1,2,3", arr is unchanged

Enter fullscreen mode Exit fullscreen mode

toLocaleString(): Returns a string representing the elements of the array. The elements are converted to strings using their toLocaleString methods.

let arr = [1000, 200];
let str = arr.toLocaleString('en-US'); // str is "1,000,200", arr is unchanged

Enter fullscreen mode Exit fullscreen mode

flat(): Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

let arr = [1, [2, 3], [4, [5]]];
let newArr = arr.flat(2); // newArr is [1, 2, 3, 4, 5], arr is unchanged

Enter fullscreen mode Exit fullscreen mode

flatMap(): Returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level.

let arr = [1, 2, 3];
let newArr = arr.flatMap(x => [x, x * 2]); // newArr is [1, 2, 2, 4, 3, 6], arr is unchanged

Enter fullscreen mode Exit fullscreen mode

at() (ES2022): Takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.

let arr = [1, 2, 3];
let element = arr.at(-1); // element is 3, arr is unchanged

Enter fullscreen mode Exit fullscreen mode

toReversed() (ES2023): Returns a new array with the elements in reversed order. This is the non-mutating counterpart of reverse().

let arr = [1, 2, 3];
let newArr = arr.toReversed(); // newArr is [3, 2, 1], arr is unchanged

Enter fullscreen mode Exit fullscreen mode

toSorted() (ES2023): Returns a new array with the elements sorted in ascending order. This is the non-mutating counterpart of sort().

let arr = [3, 1, 4, 1, 5];
let newArr = arr.toSorted(); // newArr is [1, 1, 3, 4, 5], arr is unchanged

Enter fullscreen mode Exit fullscreen mode

toSpliced() (ES2023): Returns a new array with some elements removed and/or replaced at a given index. This is the non-mutating counterpart of splice().

let arr = [1, 2, 3, 4, 5];
let newArr = arr.toSpliced(2, 1, 6, 7); // newArr is [1, 2, 6, 7, 4, 5], arr is unchanged

Enter fullscreen mode Exit fullscreen mode

with() (ES2023): Returns a new array with the element at the given index replaced with the given value.

let arr = [1, 2, 3];
let newArr = arr.with(1, 99); // newArr is [1, 99, 3], arr is unchanged

Enter fullscreen mode Exit fullscreen mode

Array.from(): Creates a new, shallow-copied Array instance from an array-like or iterable object.

let str = "abc";
let arr = Array.from(str); // arr is ['a', 'b', 'c']

Enter fullscreen mode Exit fullscreen mode

Array.isArray(): Determines whether the passed value is an Array.

Array.isArray([1, 2, 3]); // true

Enter fullscreen mode Exit fullscreen mode

Array.of(): Creates a new Array instance from a variable number of arguments, regardless of number or type of the arguments.

Array.of(1, 2, 3); // [1, 2, 3]

Enter fullscreen mode Exit fullscreen mode

Object.groupBy() (ES2024): This is a static method that groups the elements of an iterable according to the string values returned by a provided callback function. It returns an object with the groups.

const array = [{ name: 'Alice', age: 30 }, { name: 'Bob', age: 25 }, { name: 'Charlie', age: 30 }];
const groupedByAge = Object.groupBy(array, ({ age }) => age);
// groupedByAge will be:
// {
//   '30': [{ name: 'Alice', age: 30 }, { name: 'Charlie', age: 30 }],
//   '25': [{ name: 'Bob', age: 25 }]
// }
// The original array is not mutated.

Enter fullscreen mode Exit fullscreen mode

Map.groupBy() (ES2024): Similar to Object.groupBy(), but returns a Map instance instead of an object. This is useful when the keys for grouping might not be valid object keys (e.g., symbols, or numbers that you want to keep as numbers).

const array = [{ type: 'fruit', name: 'apple' }, { type: 'vegetable', name: 'carrot' }, { type: 'fruit', name: 'banana' }];
const groupedByType = Map.groupBy(array, ({ type }) => type);
// groupedByType will be a Map:
// Map {
//   'fruit' => [{ type: 'fruit', name: 'apple' }, { type: 'fruit', name: 'banana' }],
//   'vegetable' => [{ type: 'vegetable', name: 'carrot' }]
// }
// The original array is not mutated.

Enter fullscreen mode Exit fullscreen mode

Key Takeaway:

The introduction of toReversed(), toSorted(), and toSpliced() in ES2023 (and now part of ES2024 standard) is a significant step towards encouraging immutability in JavaScript array operations, providing non-mutating alternatives to their long-standing mutating counterparts.

📌📌 Moe Javascript related topics and interview questions here:
Tricky javascript code part 3

Top comments (0)