Methods of manipulating arrays in JS (full)

Directory

1. Array.of()

2. Array.prototype.pop()

3. Array.prototype.push()

4. Array.prototype.reduce()

5. Array.prototype.reduceRight()

6. Array.prototype.reverse()

7. Array.prototype.shift()

8. Array.prototype.slice()

9. Array.prototype.some()

10. Array.prototype.sort()

11. Array.prototype.splice()

12. Array.prototype.toLocaleString()

13. Array.prototype.toReversed()

14. Array.prototype.toSorted()

15. Array.prototype.toSpliced()

16. Array.prototype.toString()

17. Array.prototype.unshift()

18. Array.prototype.at()

19. Array.prototype.concat()

20. Array.prototype.copyWithin()

21. Array.prototype.entries()

22. Array.prototype.every()

23. Array. prototype. fill()

24. Array.prototype.filter()

25. Array.prototype.find()

26. Array.prototype.findIndex()

27. Array.prototype.findLast()

28. Array.prototype.findLastIndex()

29. Array. prototype. flat()

30. Array.prototype.flatMap()

31. Array.prototype.forEach()

32. Array. from()

33. Array.prototype.indexOf()

34. Array. isArray()

35. Array. prototype. join()

36. Array.prototype.keys()

37. Array.prototype.map()


1.Array.of()

The Array.of() static method creates a new Array instance with a variable number of arguments, regardless of the number or types of arguments.

console.log(Array.of('foo', 2, 'bar', true));
// Expected output: Array ["foo", 2, "bar", true]

console.log(Array.of());
// Expected output: Array []

2.Array.prototype.pop()

The pop() method removes the last element from the array and returns the value of that element. This method changes the length of the array.

const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
// Expected output: "tomato"

console.log(plants);
// Expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

plants. pop();

console.log(plants);
// Expected output: Array ["broccoli", "cauliflower", "cabbage"]

3.Array.prototype.push()

The push() method adds the specified element to the end of the array and returns the new array length.

const animals = ['pigs', 'goats', 'sheep'];

const count = animals. push('cows');
console. log(count);
// Expected output: 4
console. log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows"]

animals.push('chickens', 'cats', 'dogs');
console. log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]

4.Array.prototype.reduce()

The reduce() method sequentially executes a provided reducer function for each element in the array, and runs the reducer each time strong> will pass in the result of the computation of previous elements as an argument, and finally aggregate their results into a single return value.

When the callback function is executed for the first time, there is no “last calculation result”. If the callback function needs to be executed from the element whose index is 0, the initial value needs to be passed. Otherwise, the element at index 0 of the array will be used as the initial value, and the iterator will start executing from the second element (i.e. start at index 1 instead of 0).

The following example can help you understand the usefulness of reduce() – calculating the sum of all elements of an array:

const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1. reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  initialValue
);

console.log(sumWithInitial);
// Expected output: 10

5.Array.prototype.reduceRight()

The reduceRight() method applies a function to the accumulator and each value of the array (in right-to-left order) and makes it a single value.

For a similar method for traversing from left to right, see Array.prototype.reduce().

const array1 = [[0, 1], [2, 3], [4, 5]];

const result = array1.reduceRight((accumulator, currentValue) => accumulator.concat(currentValue));

console. log(result);
// Expected output: Array [4, 5, 2, 3, 0, 1]

6.Array.prototype.reverse()

The reverse() method reverses the elements of an array in-place and returns a reference to the same array. The first element of the array becomes the last, and the last element of the array becomes the first. In other words, the order of the elements in the array will be flipped to the opposite direction.

To reverse the elements in an array without changing the original array, use toReversed().

const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// Expected output: "array1:" Array ["one", "two", "three"]

const reversed = array1. reverse();
console.log('reversed:', reversed);
// Expected output: "reversed:" Array ["three", "two", "one"]

// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1);
// Expected output: "array1:" Array ["three", "two", "one"]

7.Array.prototype.shift()

The shift() method removes the first element from the array and returns the value of that element. This method changes the length of the array.

const array1 = [1, 2, 3];

const firstElement = array1. shift();

console. log(array1);
// Expected output: Array [2, 3]

console. log(firstElement);
// Expected output: 1

8.Array.prototype.slice()

The slice() method returns a new array object that is determined by start and end A shallow copy of the original array (including start, excluding end), where start and end represent array elements index of. The original array will not be changed.

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console. log(animals. slice(2));
// Expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// Expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// Expected output: Array ["bison", "camel", "duck", "elephant"]

console. log(animals. slice(-2));
// Expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// Expected output: Array ["camel", "duck"]

console. log(animals. slice());
// Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

9.Array.prototype.some()

The some() method tests whether at least one element in the array passes the test implemented by the provided function. Returns true if an element is found in the array such that the provided function returns true; otherwise returns false. It doesn’t modify the array.

const array = [1, 2, 3, 4, 5];

// Checks whether an element is even
const even = (element) => element % 2 === 0;

console. log(array. some(even));
// Expected output: true

10.Array.prototype.sort()

The sort() method sorts the elements of an array in-place and returns a reference to the same array. The default sort is to convert the elements to strings and sort them in ascending order of their UTF-16 code unit value.

Since it depends on the specific implementation, there are no guarantees about the time and space complexity of the sort.

If you want to keep the sorting method of the original array, you can use toSorted().

const months = ['March', 'Jan', 'Feb', 'Dec'];
months. sort();
console. log(months);
// Expected output: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1, 30, 4, 21, 100000];
array1. sort();
console. log(array1);
// Expected output: Array [1, 100000, 21, 30, 4]

11.Array.prototype.splice()

The splice() method changes the contents of an array in-place by removing or replacing existing elements and/or adding new elements.

To create a new array with parts removed and/or replaced without changing the original array, use toSpliced(). To access a portion of an array without modifying it, see slice().

const months = ['Jan', 'March', 'April', 'June'];
months. splice(1, 0, 'Feb');
// Inserts at index 1
console. log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "June"]

months. splice(4, 1, 'May');
// Replaces 1 element at index 4
console. log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "May"]

12.Array.prototype.toLocaleString()

The toLocaleString() method returns a string representing all elements in the array. Each element is converted to a string by calling its own toLocaleString method, and is separated by a locale-specific string (such as a comma “,”).

const array1 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')];
const localeString = array1.toLocaleString('en', { timeZone: 'UTC' });

console.log(localeString);
// Expected output: "1,a,12/21/1997, 2:12:00 PM",
// This assumes "en" locale and UTC timezone - your results may vary

13.Array.prototype.toReversed()

The toReversed() method of an Array instance is a duplicated version of the reverse() method. It returns a new array with elements in reverse order.

toReversed()

14.Array.prototype.toSorted()

The toSorted() method of an Array instance is a duplicate method version of the sort() method. It returns a new array with elements in ascending order.

// do not pass in the function
toSorted()

// Pass in the arrow function
toSorted((a, b) => { /* ... */ })

// pass in comparison function
toSorted(compareFn)

// inline comparison function
toSorted(function compareFn(a, b) { /* … */ })

15. Array.prototype.toSpliced()

The toSpliced() method of an Array instance is a duplicated version of the splice() method. It returns a new array with some elements removed and/or replaced at the given index.

toSpliced(start)
toSpliced(start, deleteCount)
toSpliced(start, deleteCount, item1)
toSpliced(start, deleteCount, item1, item2, itemN)

16. Array.prototype.toString()

The toString() method returns a string representing the specified array and its elements.

const array1 = [1, 2, 'a', '1a'];

console.log(array1.toString());
// Expected output: "1,2,a,1a"

17.Array.prototype.unshift()

The unshift() method adds the specified element to the beginning of the array and returns the new length of the array.

const array1 = [1, 2, 3];

console.log(array1.unshift(4, 5));
// Expected output: 5

console. log(array1);
// Expected output: Array [4, 5, 1, 2, 3]

18.Array.prototype.at()

The at() method takes an integer value and returns the element at that index, both positive and negative numbers are allowed. Negative integers count backwards from the last element in the array.

const array1 = [5, 12, 8, 130, 44];

let index = 2;

console.log(`Using an index of ${index} the item returned is ${array1.at(index)}`);
// Expected output: "Using an index of 2 the item returned is 8"

index = -2;

console.log(`Using an index of ${index} item returned is ${array1.at(index)}`);
// Expected output: "Using an index of -2 item returned is 130"

19.Array.prototype.concat()

The concat() method is used to combine two or more arrays. This method does not alter the existing array, but returns a new array.

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console. log(array3);
// Expected output: Array ["a", "b", "c", "d", "e", "f"]

20.Array.prototype.copyWithin()

The copyWithin() method shallow copies a portion of an array to another location within the same array and returns it without changing the length of the original array.

const array1 = ['a', 'b', 'c', 'd', 'e'];

// Copy to index 0 the element at index 3
console.log(array1.copyWithin(0, 3, 4));
// Expected output: Array ["d", "b", "c", "d", "e"]

// Copy to index 1 all elements from index 3 to the end
console.log(array1.copyWithin(1, 3));
// Expected output: Array ["d", "d", "e", "d", "e"]

21.Array.prototype.entries()

The entries() method returns a new Array Iterator (en-US) object containing key/value pairs for each index in the array.

const array1 = ['a', 'b', 'c'];

const iterator1 = array1. entries();

console.log(iterator1.next().value);
// Expected output: Array [0, "a"]

console.log(iterator1.next().value);
// Expected output: Array [1, "b"]

22.Array.prototype.every()

The every() method tests whether all elements in an array pass the test of the specified function. It returns a boolean value.

const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// Expected output: true

23.Array.prototype.fill()

The fill() method fills an array with a fixed value from the start index (default is 0) to the end index (default is array.length) of all elements. It returns the modified array.

const array1 = [1, 2, 3, 4];

// Fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// Expected output: Array [1, 2, 0, 0]

// Fill with 5 from position 1
console.log(array1.fill(5, 1));
// Expected output: Array [1, 5, 5, 5]

console.log(array1.fill(6));
// Expected output: Array [6, 6, 6, 6]

24.Array.prototype.filter()

The filter() method creates a shallow copy of a portion of the given array that contains all elements that pass the tests implemented by the provided function.

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words. filter(word => word. length > 6);

console. log(result);
// Expected output: Array ["exuberant", "destruction", "present"]

25.Array.prototype.find()

The find() method returns the value of the first element in the array that satisfies the provided test function. Otherwise returns undefined. If you need to find the index of the corresponding element in the array, use findIndex(). If you need to find the index of a value, use Array.prototype.indexOf(). (It’s similar to findIndex(), but just checks each element for equality with a value instead of using a test function.) If you need to find whether a value exists in an array, use Array.prototype. includes(). Also, it checks each element for equality with a value instead of using a test function. If you need to find whether an element satisfies the provided test function, use Array.prototype.some().

const array1 = [5, 12, 8, 130, 44];

const found = array1. find(element => element > 10);

console. log(found);
// Expected output: 12

26.Array.prototype.findIndex()

The findIndex() method returns the index of the first element in the array that satisfies the provided test function. Returns -1 if no corresponding element is found.

See also the find() method, which returns the first element (not its index) that satisfies the test function.

const array1 = [5, 12, 8, 130, 44];

const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
// Expected output: 3

27.Array.prototype.findLast()

The findLast() method iterates over the array in reverse and returns the value of the first element that satisfies the provided test function. Returns undefined if no corresponding element is found

If you need to find:

  • The first matching element, using find().
  • The index of the last matching element in the array, using findLastIndex().
  • The index of a value, using indexOf(). (It’s similar to findIndex(), but instead of using a test function, each element is checked for equality.)
  • Whether a value exists in the array, using includes(). Likewise, it checks each element for equality, rather than using a test function.
  • Whether any element satisfies the provided test function, using some()
const array1 = [5, 12, 50, 130, 44];

const found = array1. findLast((element) => element > 45);

console. log(found);
// Expected output: 130

28.Array.prototype.findLastIndex()

The findLastIndex() method iterates over the array in reverse and returns the index of the first element that satisfies the provided test function. If no corresponding element is found, -1 is returned.

See also the findLast() method, which returns the value (rather than its index) of the last element satisfying the test function.

const array1 = [5, 12, 50, 130, 44];

const isLargeNumber = (element) => element > 45;

console.log(array1.findLastIndex(isLargeNumber));
// Expected output: 3
// Index of element with value: 130

29.Array.prototype.flat()

The flat() method creates a new array and recursively flattens all subarray elements into the new array according to the specified depth.

const arr1 = [0, 1, 2, [3, 4]];

console.log(arr1.flat());
// Expected output: Array [0, 1, 2, 3, 4]

const arr2 = [0, 1, 2, [[[3, 4]]]];

console.log(arr2.flat(2));
// Expected output: Array [0, 1, 2, Array [3, 4]]

30.Array.prototype.flatMap()

The flatMap() method applies the given callback function to each element in the array, then flattens the result one level, returning a new array. It is equivalent to calling the flat() method with a depth of 1 (arr.map(...args).flat()) after calling the map() method, but it is better than calling these two This method is slightly more efficient.

const arr1 = [1, 2, 1];

const result = arr1. flatMap((num) => (num === 2 ? [2, 2] : 1));

console. log(result);
// Expected output: Array [1, 2, 2, 1]

31.Array.prototype.forEach()

The forEach() method executes the given function once for each element of the array.

const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

// Expected output: "a"
// Expected output: "b"
// Expected output: "c"

32.Array.from()

The Array.from() static method creates a new shallow copy of the Array instance from an iterable or array-like object.

To convert an asynchronous iterable to an array, use Array.fromAsync().

console.log(Array.from('foo'));
// Expected output: Array ["f", "o", "o"]

console.log(Array.from([1, 2, 3], x => x + x));
// Expected output: Array [2, 4, 6]

33.Array.prototype.indexOf()

The indexOf() method returns the index of the first occurrence of the given element in the array, or -1 if it does not exist.

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// Expected output: 1

// Start from index 2
console.log(beasts.indexOf('bison', 2));
// Expected output: 4

console.log(beasts.indexOf('giraffe'));
// Expected output: -1

34.Array.isArray()

The Array.isArray() static method is used to determine whether the passed value is an Array.

console.log(Array.isArray([1, 3, 5]));
// Expected output: true

console.log(Array.isArray('[]'));
// Expected output: false

console.log(Array.isArray(new Array(5)));
// Expected output: true

console.log(Array.isArray(new Int16Array([15, 33])));
// Expected output: false

35.Array.prototype.join()

The join() method joins all elements of an array (or an array-like object) into a string and returns the string, separated by a comma or the specified delimiter character string separated. If the array has only one element, then that element will be returned without a separator.

const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// Expected output: "Fire,Air,Water"

console.log(elements.join(''));
// Expected output: "FireAirWater"

console.log(elements.join('-'));
// Expected output: "Fire-Air-Water"

36.Array.prototype.keys()

The keys() method returns a new Array Iterator (en-US) object containing the keys for each index in the array.

const array1 = ['a', 'b', 'c'];
const iterator = array1. keys();

for (const key of iterator) {
  console. log(key);
}

// Expected output: 0
// Expected output: 1
// Expected output: 2

37.Array.prototype.map()

The map() method creates a new array that is returned by calling the provided function once for each element in the original array value composition.

const array1 = [1, 4, 9, 16];

// Pass a function to map
const map1 = array1. map(x => x * 2);

console. log(map1);
// Expected output: Array [2, 8, 18, 32]