tutorials & docs,tools & experiences for developers

Full List Of JavaScript Array Operation Methods

ECMAScript provides a number of methods for manipulating items which are have contained in an array. Here I summarize my understanding of these methods in this post. I will classify the methods according to whether the original array will be changed, and then explain each method one by one.

The Original Array Won't be Changed

1. concat()

Syntax: array.concat(array2,array3,...,arrayX)

Returned value: Return a new array

The concat() method is used to join two or more arrays. The method won't change the existing array, and what it returns is only a copy of the joined array.

In the absence of a parameter passed, it simply copies the current array and returns a copy; and if the value passed is not an array, these values ​​will be added simply to the end of the result array.

var arr1 = [1,2,3];
var arr2 = arr1.concat(4,[5,6]);

console.log(arr1);  // [ 1, 2, 3 ]
console.log(arr2);  // [ 1, 2, 3, 4, 5, 6 ]

2. join()

Syntax: array.join(separator)

Returned value: return a string

The join() method is used to put all the elements from the array into a string. The elements are separated by the specified separator, and the ',' is used by default, without changing the original array.

var arr1 = [1,2,3];
var arr2 = arr1.join();

console.log(arr1);  // [ 1, 2, 3 ]
console.log(arr2);  // 1,2,3

I have come across a function which needs to generate multiple consecutive *. At first, I used the for loop, but when I have learnt the join() method, I find that I can get it done in one statement.

var arr3 = "";
for(let i = 0; i < 15; i ++) {
    arr3 = arr3 + "*";
}
console.log(arr3);  // ***************

var arr4 = new Array(16).join("*");
console.log(arr4);  // ***************

3. slice()

Syntax: array.slice(start, end)

Returned Value: Return a new array containing the elements from the start to the end (except this element) in arrayObject.

The slice() method accepts one or two arguments, which are the start and end of the items to be returned.

When there is only one parameter, the slice() method will return all the items that are from the specified position of the parameter to the end of the current array; If there are two arguments, the method will return the items between the start and end positions, not including the item at the end position.

If the argument is negative, the position will be counted from the end of the array, which means that -1 refers to the last element, -2 refers to the second last element, and so on.

var arr1 = [1,2,3,4,5,6];
var arr2 = arr1.slice(1);
var arr3 = arr1.slice(2,4);
var arr4 = arr1.slice(-4,-2);  // Equal to arr1.slice(2,4);

console.log(arr1);  // [ 1, 2, 3, 4, 5, 6 ]
console.log(arr2);  // [ 2, 3, 4, 5, 6 ]
console.log(arr3);  // [ 3, 4 ]
console.log(arr4);  // [ 3, 4 ]

And this method is also used for converting a pseudo array to standard array.

Array.prototype.slice.call(arguments)

4. some()

Syntax: array.some(function(currentValue,index,arr),thisValue)

Returned value: Boolean

The some() method runs the given function on each item in the array. If the function returns true for any item, the remaining elements will not be tested again; if there are no elements that satisfy the condition, it returns false.

function compare(item, index, arr){
    return item > 10;
}

[2, 5, 8, 1, 4].some(compare);  // false
[20, 5, 8, 1, 4].some(compare);  // true

5. every()

Syntax: array.every(function(currentValue,index,arr),thisValue)

Returned value: Boolean

The every() method runs the given function on each item in the array. If the function returns true for each item, the remaining elements will not be tested again; if one of the elements does not satisfy the condition, then it returns false.

function compare(item, index, arr){
    return item > 10;
}

[20, 50, 80, 11, 40].every(compare);  // true
[20, 50, 80, 10, 40].every(compare);  // false

6. filter()

Syntax: array.filter(function(currentValue,index,arr), thisValue)

Returned value: Return an array

The filter() method creates a new array, and the elements in the new array are gotten by checking all the elements in the specified array that meet the condition.

The method runs the given function on each item of the array, and returns an array of items with the result of true.

function filterArr(item, index, arr){
    return item > 4;
}

[2, 5, 8, 1, 4].filter(filterArr);  // [5,8]

7. find() - a new method in ES6

Syntax: array.find(function(currentValue, index, arr),thisValue)

Returned Value: Return the value of the first element that meet the test condition. If none meets the condition, it returns undefined.

The find() method passes in a callback function, and then finds the first element in the array that matches the current searching condition to returns it before terminating the searching.

The differences between the filter() and find() methods are:

  • The filter() method checks every item in the array and returns an array whose results of the elements are true. The find() method returns the element immediately when it finds the matched element, and the subsequent elements are no longer checked.
  • The filter() method returns an empty array if it doesn't find a matched element; and the find() method returns undefined if it doesn't find a matched element.
function filterArr(item, index, arr){
    return item > 4;
}

[2, 5, 8, 1, 4].filter(filterArr);  // [5,8]
[2, 5, 8, 1, 4].find(filterArr); // 5

function findArr(item, index, arr){
    return item > 10;
}

[2, 5, 8, 1, 4].filter(findArr);  // []
[2, 5, 8, 1, 4].find(findArr); // undefined

8. map()

Syntax: array.map(function(currentValue,index,arr), thisValue)

Returned value: Return an array

The map() method returns a new array, and the elements in the new array are the values of the original array elements that have been handled by the function.

function mapArr(item, index, arr){
    return item * 4;
}

[2, 5, 8, 1, 4].map(mapArr);  // [8,20,32,4,16]

A question which is often asked during written tests and interviews is to achieve a map array method, and here is a way I wrote.

var arr = [2, 4, 8, 6, 1];

Array.prototype.myMap = function (fn, thisValue) {
    var arr = this,
        len = arr.length,
        tmp = 0,
        result = [];
    thisValue = thisValue || null;
    for (var i = 0; i < len; i++) {
        var item = arr[i],
            index = i;
        tmp = fn.call(thisValue, item, index, arr);
        result.push(tmp);
    }
    return result
}

function mapArr(item, index, arr) {
    return item * 4;
}
arr.myMap(mapArr)   // [8, 16, 32, 24, 4]

9. forEach()

Syntax: array.forEach(function(currentValue, index, arr),

Returned value: undefined

The forEach() method is used to call each element of the array and pass the elements to the callback function. The method has no returned value.

Essentially it's the same as using for loop to iterate over an array.

var items = [1, 2, 4, 7, 3];
var copy = [];

items.forEach(function(item,index){
  copy.push(item*index);
})

console.log(items);  // [ 1, 2, 4, 7, 3 ]
console.log(copy);  // [ 0, 2, 8, 21, 12 ]

10. reduce() and reduceRight()

Syntax: array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

Returned value: Return the calculation result

Parameter Description
function(total,currentValue, index,arr) Required. A function which is used to execute each array element.
initialValue Optional. The initial value which is passed to the function.

Function parameter

Parameter Description
total Required. The initial value; or the returned value after the calculation ends.
currentValue Required. The current element
currentIndex Optional. The index of the current element
arr Optional. The array object to which the current element belongs.

Both of the two methods will iterate over all the items of the array and then construct a final returned value. And the reduce() method starts from the first item of the array and then traverses to the end one by one; while the reduceRight() starts from the last item of the array and then traverses to the first item.

If initialValue is not set, the value of total will be the first item in the array, and currentValue is the second item in the array.

If initialValue has been set, the value of total is exactly initialValue, and currentValue will be the first item in the array.

var numbers = [65, 44, 12, 4];
 
function getSum(total,currentValue, index,arr) {
    return total + currentValue;
}

var res = numbers.reduce(getSum);

console.log(numbers);  // [ 65, 44, 12, 4 ]
console.log(res);  //  125

var numbers = [65, 44, 12, 4];
 
function getSum(total,currentValue, index,arr) {
    return total + currentValue;
}

var res = numbers.reduce(getSum, 10);  // The initial value is set to 10, so the final result should be increased by 10 too.

console.log(res);  //  135

11. indexOf() and lastIndexOf()

Syntax: array.indexOf(item,start)

Returned value: The position of the element in the array, or return -1 if not found.

Both the indexOf() and lastIndexOf() methods take two arguments: the item to find and, the index of starting position for searching (optional).

The indexOf() method starts searching from the beginning of the array; while the lastIndexOf() method starts searching from the end of the array.

var n = [1,2,3,4,5,4,3,2,1];

console.log(n.indexOf(4));  // 3
console.log(n.lastIndexOf(4));  // 5

console.log(n.indexOf(4,4));  // 5
console.log(n.lastIndexOf(4,4));  // 3

indexOf() can be used to remove duplicates in an array as follows:

var n = [1, 2, 3, 4, 5, 4, 3, 2, 1];
function fn(arr) {
    var result = [],
        len = arr.length;
    for (var i = 0; i < len; i++) {
        var item = arr[i];
        if (result.indexOf(item) < 0) {
            result.push(item);
        }
   }
    return result;
}
console.log(fn(n));  // [1, 2, 3, 4, 5]

The Original Array Will be Changed.

1. Push()

Syntax: array.push(item1, item2, ..., itemX)

Returned value: Return the length of the new array

The push() method can add one or more elements to the end of the array and return the new length.

var arr= [65, 44, 12, 4];
var arr1 = arr.push(2,5);

console.log(arr); // [ 65, 44, 12, 4, 2, 5 ]
console.log(arr1); // 6

2. pop()

Syntax: array.pop()

Returned value: Return the value of the original last element of the array (the removed element)

The pop() method is used to delete and return the last element of the array. The original array will be changed.

var arr = [65, 44, 12, 4];
var arr1 = arr.pop();

console.log(arr); // [ 65, 44, 12 ]
console.log(arr1); //  4

3. unshift()

Syntax: array.unshift(item1,item2, ..., itemX)

Returned value: Return the length of the new array

The unshift() method adds one or more elements to the beginning of the array and returns the new length. The original array will be changed.

var arr = [65, 44, 12, 4];
var arr1 = arr.unshift(1);

console.log(arr); // [ 1, 65, 44, 12, 4 ]
console.log(arr1); //  5

4. shift()

Syntax: array.shift()

Returned value: Return the value of the original first element of the array (the removed element)

The shift() method is used to remove the first element of the array and return it. The original array will be changed.

var arr = [65, 44, 12, 4];
var arr1 = arr.shift();

console.log(arr); // [ 44, 12, 4 ]
console.log(arr1); //   65

5. sort()

Syntax: array.sort(sortfunction)

Returned value: Return the sorted array (in ascending order by default )

The sort() method is used to sort the elements of an array. It can be sorted alphabetically or numerically, and sorted in ascending or descending order. And it will be sorted is in alphabetically ascending order by default.

P.S.: Since It's sorted by the order of Unicode code, when sorting numbers, "10" will appear in front of "5". So you must pass a function as a parameter when sorting numbers.

var values = [0, 1, 5, 10, 15];
values.sort();
console.log(values);  // [ 0, 1, 10, 15, 5 ]

values.sort(function(a, b){
  return a - b;
})
console.log(values);  //  [0, 1, 5, 10, 15 ]

6. reverse()

Syntax: array.reverse()

Returned value: Return the inverted array

The reverse() method is used to reverse the order of the elements in the array. What it returns is the inverted array, and the original array will be changed.

var values = [0, 1, 5, 10, 15];
values.reverse();
console.log(values);  // [ 15, 10, 5, 1, 0 ]

7. fill() —— a new method in ES6

Syntax: array.fill(value, start, end)

Returned value: Return a new filled array

The fill() method is used to replace the elements in the array with a specified value.

Parameter Description
value Required. The value to be filled.
start Optional. The starting position to be filled.
end Optional. The end position to be filled (not included) ( array.length by default).
var values = [0, 1, 5, 10, 15];
values.fill(2);
console.log(values);  // [ 2, 2, 2, 2, 2 ]

values = [0, 1, 5, 10, 15];
values.fill(2,3,4);
console.log(values);  // [ 0, 1, 5, 2, 15 ]

8. splice()

Syntax: array.splice(index,howmany,item1,.....,itemX)

Returned value: What it will return is an array containing the deleted element if an element is removed from arrayObject.

Splice() can be used to:

  1. delete: You can delete any number of items by just specifying 2 parameters: the position of the first item to delete and the number of the items to delete. For example, splice(0,2) // It will remove the first two items of the array.
  2. insert: You can insert any number of items into a specified position by just providing three parameters: the starting position, 0 (the number of items to delete), and the item to insert. If you want to insert multiple items, you can pass in four, five, and even any number of items. For example, splice(2,0,1,4) // It will insert 1 and 4 from the position 2 in the array.
  3. replace: You can insert any number of items into a specified position and delete any number of items at the same time, by just providing only three parameters: the starting position, the number of items to delete, and the item to insert. The inserted number of items don't have to be equal to the number of items deleted. For example, splice(2,3,1,4) // It will remove three items in the array from position 2, and then insert 1 and 4 from position 2.
// delete
var values = [4,8,0,3,7];
var remove = values.splice(3,1);
console.log(values);  // [ 4, 8, 0, 7 ]
console.log(remove);  // [ 3 ]    Delete the fourth item.
// insert
remove = values.splice(2,0,1,2);
console.log(values);  // [ 4, 8, 1, 2, 0, 7 ]
console.log(remove);  // []  Insert two items starting at position 2, and it returns an empty function since none have been deleted.
// replace
remove = values.splice(2,2,6,9,10);
console.log(values);  // [ 4, 8, 6, 9, 10, 0, 7 ]
console.log(remove);  // [ 1, 2 ]  Remove two items from position 2 and insert three items at the same time.

9. copyWithin() - a new method in ES6

Syntax: array.copyWithin(target, start, end)

Returned value: Return a newly copied array

The copyWithin() method can be used to select a certain subscript of the array, and then copy the array elements from the position. The default is to copy from 0. You can also specify the range of elements to copy.

var fruits = [1,2,3,4,5,6];
fruits.copyWithin(1);  // [ 1, 1, 2, 3, 4, 5 ]   Copy the array starting with the element with a subscript of 1.

fruits.copyWithin(3, 0, 3);  // [ 1, 2, 3, 1, 2, 3 ]  Copy the array with array coordinates of 0 to 2 starting with the element with a subscript of 3.

Others

1. from() - a new method in ES6

Syntax: Array.from(object, mapFunction, thisValue)

Returned value: an array object

The from() method is used to return an array for a string, an object with a length property (a pseudo-array), or an iterable object (Set/Map) .

var myArr = Array.from("RUNOOB");
var s = new Set(['A', 'B', 'C']);
var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);
var s1 = Array.from(s);
var m1 = Array.from(m);

console.log(myArr);  // [ "R", "U", "N", "O", "O", "B" ]
console.log(s1);  // [ "A", "B", "C" ]
console.log(m1);  // [ [ 1, "x" ], [ 2, "y" ], [ 3, "z" ]]

In addition to Array.prototype.slice.call(arguments), you can also use the following method to convert a pseudo-array to standard array:

function test(){
     var arg = Array.from(arguments);
     arg.push(5);
     console.log(arg);  // [ 1, 2, 3, 4, 5 ]
}
test(1,2,3,4);

You can also combine with the new Set() method to remove duplicates for the array.

function dedupe(array){
     return Array.from(new Set(array));
}
dedupe([1,1,2,3]) //[1,2,3]

0 Comment

temp