Which Array Methods Do Not Change the Original Array in JavaScript?
The majority of JavaScript array methods do not mutate the original array. They will typically return a copy of the original array as modified by the method. Others return an index or a value.
Because the original array is not altered, you may wish to store the returned array (or other return value) to have it available in memory:
const array2 = array1.method(arg);
...or apply additional processing and then store or use that result:
const array2 = array1.method1(arg).method2();
Because there are so many array methods, it’s easier to memorize the small number of javascript methods that DO mutate the original array, knowing that the rest do not.
Below we’ll have a look at some of the methods that don’t mutate the original array. You may wish to visit some of the helpful references linked at the bottom of this page for a more complete list.
How do you locate an item in an array?
You can either 1) ask for a boolean response (true or false) or 2) ask for the array’s index (numerical key) for the item:
- Array.includes(item, fromIndex) - returns true if at least one item matches, using strict equality. Otherwise returns false. The optional fromIndex argument moves the starting point, excluding array items before this point.
- Array.indexOf(item, fromIndex) - returns the numerical index of the first matched item, also using strict equality. If there’s no match then the function returns -1 (which is a falsy value). Again, fromIndex is optional.
- Array.lastIndexOf(item, fromIndex) - returns the numerical index of the first matched item searching from the end of the array (right to left), also using strict equality. If there’s no match then the function returns -1 (which is a falsy value). The optional fromIndex argument sets the search starting point.
- Array.findIndex(testFn, this) - returns the numerical index of the item matched by a test function. Returns -1 if a match is not found. The optional this argument can alter the context of the function (not available if using arrow function notation). The callback function can receive up to three arguments (element, index, array) , but only the first argument is required. Since the match is determined by your callback function, you can determine how strict it needs to be.
Bonus! If you want to know what item is stored at a certain index number, you can use square bracket notation to request it:
const array = [1,2,3];
console.log(array[0]); // logs: 1
How do you test items in an array?
If you’re not exactly sure what you’re looking for but you have some parameters, you may wish to test the array items. Depending on the method you select, you can expect a boolean value or the value(s) that pass the test, or processed values. Each of these methods and their associated callback functions will accept the same three arguments described above for findIndex:
- Array.some(testFn, this) - returns true if any item in the array passes the test. Otherwise, the returned value is false.
- Array.every(testFn, this) - returns true only if every item in the array passes the test. Otherwise, the returned value is false.
- Array.find(testFn, this) - returns the first item that passes a test. If there are no matches then the returned value is undefined (another falsy value).
- Array.filter(testFn, this) - returns a new array containing all items that pass. If there are no matches, then the returned value is an empty Array.
The test function in the above examples is known as a callback function . With array methods, you must pass an argument to the callback function. It can be any word. Since this argument represents the array item during the iteration, our example below uses the word "item."
Example of a callback function:
const array1 = [1,2,3];
const array2 = array1.filter(function(item) {
return item < 4;
});
console.log(array2); // [1,2]
What else can you do with array items?
These methods will loop through the array and return another array, a single value, or simply use the logic to perform some other task and return undefined.
- Array.concat(arg) - appends values to the end of an array to return a new, longer array. You may pass comma-separated values or other arrays as arguments to be added to the original. If you are appending one array to another, you may be interested the spread syntax, although concat is the more performant choice.
- Array.join(separator) - returns a string made from placing each array item sequentially and separated by a comma. The optional argument allows you to change the (comma) separator, including to an empty string. If the array contains an object, the result will include the string [object Object]. If an array item is another array, the returned string will show a comma between the array items from that subarray, regardless of the value passed by the separator argument.
- Array.flat(depth) - returns an array that concatenates nested array elements into a single hierarchy. Without arguments, the flat method will flatten one nested level. By passing the optional number 2 or higher (up to "infinity"), you instruct the method to flatten deeper levels.
- Array.forEach(callbackFn, this) - executes the callback function once for each item in the array. This method always returns undefined. The iteration provided by this method injects each array item as input to the callback function. The callback function accepts the same three arguments in findIndex. Although the forEach method does not mutate the original array, it is possible to write a callback function that will.
- Array.map(callbackFn, this) - executes the callback function once for each array item. The returned value is a new array filled with returned values.
- Array.reduce(callbackFn, this) - returns a single value by executing the callback function once for each array item and feeding the output of each iteration into the next. The callback function accepts four arguments, and two are required. They are the intital value (a.k.a., previous) and the array item for the iteration. The third and fourth arguments are the array item index and the original array itself. The returned value at the end of the loop can be of any data type, having accumulated changes from processing through the iterations. See our post on Using the Array.reduce() method for more details.
- Array.reduceRight(callbackFn, this) - does the same thing as reduce, but works on the array from the end to the beginning (right to left).
- Array.slice(start, end) - returns a new array that is a chunk of the original array. The end argument is optional, and it doesn’t function as you might expect. The "end" item is not included in the returned array. For example, if you use the arguments (2,4) you'll get back an array with the values from indexes 2 and 3 only.
- Array.toLocaleString(locales, options) - returns a string of elements converted by their respective toLocaleString methods and separated by a locale-specific string (e.g., comma). The results vary from browser to browser. The arguments are optional. This function is handy for converting the presentation of values to a certain locale.
- Array.toString() - returns a string of elements converted to strings and separated by commas. The conversion to string may vary between browsers.
There’s also a group of array methods that return an array iterator object. What’s an iterator object, you say? Visit this page to learn more ahout .keys() , .values() , and .entries().
Related posts:
Helpful references:
Have feedback on this topic?