Reverse array in Javascript without mutating original array - javascript

Array.prototype.reverse reverses the contents of an array in place (with mutation)...
Is there a similarly simple strategy for reversing an array without altering the contents of the original array (without mutation)?

You can use slice() to make a copy then reverse() it
var newarray = array.slice().reverse();
var array = ['a', 'b', 'c', 'd', 'e'];
var newarray = array.slice().reverse();
console.log('a', array);
console.log('na', newarray);

In ES6:
const newArray = [...array].reverse()

Another ES6 variant:
We can also use .reduceRight() to create a reversed array without actually reversing it.
let A = ['a', 'b', 'c', 'd', 'e', 'f'];
let B = A.reduceRight((a, c) => (a.push(c), a), []);
console.log(B);
Useful Resources:
Array.prototype.reduceRight()
Arrow Functions
Comma Operator

const originalArray = ['a', 'b', 'c', 'd', 'e', 'f'];
const newArray = Array.from(originalArray).reverse();
console.log(newArray);

There are multiple ways of reversing an array without modifying. Two of them are
var array = [1,2,3,4,5,6,7,8,9,10];
// Using Splice
var reverseArray1 = array.splice().reverse(); // Fastest
// Using spread operator
var reverseArray2 = [...array].reverse();
// Using for loop
var reverseArray3 = [];
for(var i = array.length-1; i>=0; i--) {
reverseArray.push(array[i]);
}
Performance test http://jsben.ch/guftu

Try this recursive solution:
const reverse = ([head, ...tail]) =>
tail.length === 0
? [head] // Base case -- cannot reverse a single element.
: [...reverse(tail), head] // Recursive case
reverse([1]); // [1]
reverse([1,2,3]); // [3,2,1]
reverse('hello').join(''); // 'olleh' -- Strings too!

An ES6 alternative using .reduce() and spreading.
const foo = [1, 2, 3, 4];
const bar = foo.reduce((acc, b) => ([b, ...acc]), []);
Basically what it does is create a new array with the next element in foo, and spreading the accumulated array for each iteration after b.
[]
[1] => [1]
[2, ...[1]] => [2, 1]
[3, ...[2, 1]] => [3, 2, 1]
[4, ...[3, 2, 1]] => [4, 3, 2, 1]
Alternatively .reduceRight() as mentioned above here, but without the .push() mutation.
const baz = foo.reduceRight((acc, b) => ([...acc, b]), []);

const arrayCopy = Object.assign([], array).reverse()
This solution:
-Successfully copies the array
-Doesn't mutate the original array
-Looks like it's doing what it is doing

There's a new tc39 proposal, which adds a toReversed method to Array that returns a copy of the array and doesn't modify the original.
Example from the proposal:
const sequence = [1, 2, 3];
sequence.toReversed(); // => [3, 2, 1]
sequence; // => [1, 2, 3]
As it's currently in stage 3, it will likely be implemented in browser engines soon, but in the meantime a polyfill is available here or in core-js.

Reversing in place with variable swap just for demonstrative purposes (but you need a copy if you don't want to mutate)
const myArr = ["a", "b", "c", "d"];
const copy = [...myArr];
for (let i = 0; i < (copy.length - 1) / 2; i++) {
const lastIndex = copy.length - 1 - i;
[copy[i], copy[lastIndex]] = [copy[lastIndex], copy[i]]
}

Jumping into 2022, and here's the most efficient solution today (highest-performing, and no extra memory usage).
For any ArrayLike type, the fastest way to reverse is logically, by wrapping it into a reversed iterable:
function reverse<T>(input: ArrayLike<T>): Iterable<T> {
return {
[Symbol.iterator](): Iterator<T> {
let i = input.length;
return {
next(): IteratorResult<T> {
return i
? {value: input[--i], done: false}
: {value: undefined, done: true};
},
};
},
};
}
This way you can reverse-iterate through any Array, string or Buffer, without any extra copy or processing for the reversed data:
for(const a of reverse([1, 2, 3])) {
console.log(a); //=> 3 2 1
}
It is the fastest approach, because you do not copy the data, and do no processing at all, you just reverse it logically.

Is there a similarly simple strategy for reversing an array without altering the contents of the original array (without mutation) ?
Yes, there is a way to achieve this by using to[Operation] that return a new collection with the operation applied (This is currently at stage 3, will be available soon).
Implementation will be like :
const arr = [5, 4, 3, 2, 1];
const reversedArr = arr.toReverse();
console.log(arr); // [5, 4, 3, 2, 1]
console.log(reversedArr); // [1, 2, 3, 4, 5]

Not the best solution but it works
Array.prototype.myNonMutableReverse = function () {
const reversedArr = [];
for (let i = this.length - 1; i >= 0; i--) reversedArr.push(this[i]);
return reversedArr;
};
const a = [1, 2, 3, 4, 5, 6, 7, 8];
const b = a.myNonMutableReverse();
console.log("a",a);
console.log("////////")
console.log("b",b);

INTO plain Javascript:
function reverseArray(arr, num) {
var newArray = [];
for (let i = num; i <= arr.length - 1; i++) {
newArray.push(arr[i]);
}
return newArray;
}

es6:
const reverseArr = [1,2,3,4].sort(()=>1)

Related

React js Array and Array Reverse issue without mutating original array [duplicate]

Array.prototype.reverse reverses the contents of an array in place (with mutation)...
Is there a similarly simple strategy for reversing an array without altering the contents of the original array (without mutation)?
You can use slice() to make a copy then reverse() it
var newarray = array.slice().reverse();
var array = ['a', 'b', 'c', 'd', 'e'];
var newarray = array.slice().reverse();
console.log('a', array);
console.log('na', newarray);
In ES6:
const newArray = [...array].reverse()
Another ES6 variant:
We can also use .reduceRight() to create a reversed array without actually reversing it.
let A = ['a', 'b', 'c', 'd', 'e', 'f'];
let B = A.reduceRight((a, c) => (a.push(c), a), []);
console.log(B);
Useful Resources:
Array.prototype.reduceRight()
Arrow Functions
Comma Operator
const originalArray = ['a', 'b', 'c', 'd', 'e', 'f'];
const newArray = Array.from(originalArray).reverse();
console.log(newArray);
There are multiple ways of reversing an array without modifying. Two of them are
var array = [1,2,3,4,5,6,7,8,9,10];
// Using Splice
var reverseArray1 = array.splice().reverse(); // Fastest
// Using spread operator
var reverseArray2 = [...array].reverse();
// Using for loop
var reverseArray3 = [];
for(var i = array.length-1; i>=0; i--) {
reverseArray.push(array[i]);
}
Performance test http://jsben.ch/guftu
Try this recursive solution:
const reverse = ([head, ...tail]) =>
tail.length === 0
? [head] // Base case -- cannot reverse a single element.
: [...reverse(tail), head] // Recursive case
reverse([1]); // [1]
reverse([1,2,3]); // [3,2,1]
reverse('hello').join(''); // 'olleh' -- Strings too!
An ES6 alternative using .reduce() and spreading.
const foo = [1, 2, 3, 4];
const bar = foo.reduce((acc, b) => ([b, ...acc]), []);
Basically what it does is create a new array with the next element in foo, and spreading the accumulated array for each iteration after b.
[]
[1] => [1]
[2, ...[1]] => [2, 1]
[3, ...[2, 1]] => [3, 2, 1]
[4, ...[3, 2, 1]] => [4, 3, 2, 1]
Alternatively .reduceRight() as mentioned above here, but without the .push() mutation.
const baz = foo.reduceRight((acc, b) => ([...acc, b]), []);
const arrayCopy = Object.assign([], array).reverse()
This solution:
-Successfully copies the array
-Doesn't mutate the original array
-Looks like it's doing what it is doing
There's a new tc39 proposal, which adds a toReversed method to Array that returns a copy of the array and doesn't modify the original.
Example from the proposal:
const sequence = [1, 2, 3];
sequence.toReversed(); // => [3, 2, 1]
sequence; // => [1, 2, 3]
As it's currently in stage 3, it will likely be implemented in browser engines soon, but in the meantime a polyfill is available here or in core-js.
Reversing in place with variable swap just for demonstrative purposes (but you need a copy if you don't want to mutate)
const myArr = ["a", "b", "c", "d"];
const copy = [...myArr];
for (let i = 0; i < (copy.length - 1) / 2; i++) {
const lastIndex = copy.length - 1 - i;
[copy[i], copy[lastIndex]] = [copy[lastIndex], copy[i]]
}
Jumping into 2022, and here's the most efficient solution today (highest-performing, and no extra memory usage).
For any ArrayLike type, the fastest way to reverse is logically, by wrapping it into a reversed iterable:
function reverse<T>(input: ArrayLike<T>): Iterable<T> {
return {
[Symbol.iterator](): Iterator<T> {
let i = input.length;
return {
next(): IteratorResult<T> {
return i
? {value: input[--i], done: false}
: {value: undefined, done: true};
},
};
},
};
}
This way you can reverse-iterate through any Array, string or Buffer, without any extra copy or processing for the reversed data:
for(const a of reverse([1, 2, 3])) {
console.log(a); //=> 3 2 1
}
It is the fastest approach, because you do not copy the data, and do no processing at all, you just reverse it logically.
Is there a similarly simple strategy for reversing an array without altering the contents of the original array (without mutation) ?
Yes, there is a way to achieve this by using to[Operation] that return a new collection with the operation applied (This is currently at stage 3, will be available soon).
Implementation will be like :
const arr = [5, 4, 3, 2, 1];
const reversedArr = arr.toReverse();
console.log(arr); // [5, 4, 3, 2, 1]
console.log(reversedArr); // [1, 2, 3, 4, 5]
Not the best solution but it works
Array.prototype.myNonMutableReverse = function () {
const reversedArr = [];
for (let i = this.length - 1; i >= 0; i--) reversedArr.push(this[i]);
return reversedArr;
};
const a = [1, 2, 3, 4, 5, 6, 7, 8];
const b = a.myNonMutableReverse();
console.log("a",a);
console.log("////////")
console.log("b",b);
INTO plain Javascript:
function reverseArray(arr, num) {
var newArray = [];
for (let i = num; i <= arr.length - 1; i++) {
newArray.push(arr[i]);
}
return newArray;
}
es6:
const reverseArr = [1,2,3,4].sort(()=>1)

How to remove an array element with JavaScript [duplicate]

How do I remove a specific value from an array? Something like:
array.remove(value);
Constraints: I have to use core JavaScript. Frameworks are not allowed.
Find the index of the array element you want to remove using indexOf, and then remove that index with splice.
The splice() method changes the contents of an array by removing
existing elements and/or adding new elements.
const array = [2, 5, 9];
console.log(array);
const index = array.indexOf(5);
if (index > -1) { // only splice array when item is found
array.splice(index, 1); // 2nd parameter means remove one item only
}
// array = [2, 9]
console.log(array);
The second parameter of splice is the number of elements to remove. Note that splice modifies the array in place and returns a new array containing the elements that have been removed.
For the reason of completeness, here are functions. The first function removes only a single occurrence (i.e. removing the first match of 5 from [2,5,9,1,5,8,5]), while the second function removes all occurrences:
function removeItemOnce(arr, value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
function removeItemAll(arr, value) {
var i = 0;
while (i < arr.length) {
if (arr[i] === value) {
arr.splice(i, 1);
} else {
++i;
}
}
return arr;
}
// Usage
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
console.log(removeItemAll([2,5,9,1,5,8,5], 5))
In TypeScript, these functions can stay type-safe with a type parameter:
function removeItem<T>(arr: Array<T>, value: T): Array<T> {
const index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
Edited on 2016 October
Do it simple, intuitive and explicit (Occam's razor)
Do it immutable (original array stays unchanged)
Do it with standard JavaScript functions, if your browser doesn't support them - use polyfill
In this code example I use array.filter(...) function to remove unwanted items from an array. This function doesn't change the original array and creates a new one. If your browser doesn't support this function (e.g. Internet Explorer before version 9, or Firefox before version 1.5), consider polyfilling with core-js.
Removing item (ECMA-262 Edition 5 code AKA old style JavaScript)
var value = 3
var arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(function(item) {
return item !== value
})
console.log(arr)
// [ 1, 2, 4, 5 ]
Removing item (ECMAScript 6 code)
let value = 3
let arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(item => item !== value)
console.log(arr)
// [ 1, 2, 4, 5 ]
IMPORTANT ECMAScript 6 () => {} arrow function syntax is not supported in Internet Explorer at all, Chrome before version 45, Firefox before version 22, and Safari before version 10. To use ECMAScript 6 syntax in old browsers you can use BabelJS.
Removing multiple items (ECMAScript 7 code)
An additional advantage of this method is that you can remove multiple items
let forDeletion = [2, 3, 5]
let arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(item => !forDeletion.includes(item))
// !!! Read below about array.includes(...) support !!!
console.log(arr)
// [ 1, 4 ]
IMPORTANT array.includes(...) function is not supported in Internet Explorer at all, Chrome before version 47, Firefox before version 43, Safari before version 9, and Edge before version 14 but you can polyfill with core-js.
Removing multiple items (in the future, maybe)
If the "This-Binding Syntax" proposal is ever accepted, you'll be able to do this:
// array-lib.js
export function remove(...forDeletion) {
return this.filter(item => !forDeletion.includes(item))
}
// main.js
import { remove } from './array-lib.js'
let arr = [1, 2, 3, 4, 5, 3]
// :: This-Binding Syntax Proposal
// using "remove" function as "virtual method"
// without extending Array.prototype
arr = arr::remove(2, 3, 5)
console.log(arr)
// [ 1, 4 ]
Try it yourself in BabelJS :)
Reference
Array.prototype.includes
Functional composition
I don't know how you are expecting array.remove(int) to behave. There are three possibilities I can think of that you might want.
To remove an element of an array at an index i:
array.splice(i, 1);
If you want to remove every element with value number from the array:
for (var i = array.length - 1; i >= 0; i--) {
if (array[i] === number) {
array.splice(i, 1);
}
}
If you just want to make the element at index i no longer exist, but you don't want the indexes of the other elements to change:
delete array[i];
It depends on whether you want to keep an empty spot or not.
If you do want an empty slot:
array[index] = undefined;
If you don't want an empty slot:
//To keep the original:
//oldArray = [...array];
//This modifies the array.
array.splice(index, 1);
And if you need the value of that item, you can just store the returned array's element:
var value = array.splice(index, 1)[0];
If you want to remove at either end of the array, you can use array.pop() for the last one or array.shift() for the first one (both return the value of the item as well).
If you don't know the index of the item, you can use array.indexOf(item) to get it (in a if() to get one item or in a while() to get all of them). array.indexOf(item) returns either the index or -1 if not found.
A friend was having issues in Internet Explorer 8 and showed me what he did. I told him it was wrong, and he told me he got the answer here. The current top answer will not work in all browsers (Internet Explorer 8 for example), and it will only remove the first occurrence of the item.
Remove ALL instances from an array
function removeAllInstances(arr, item) {
for (var i = arr.length; i--;) {
if (arr[i] === item) arr.splice(i, 1);
}
}
It loops through the array backwards (since indices and length will change as items are removed) and removes the item if it's found. It works in all browsers.
There are two major approaches
splice(): anArray.splice(index, 1);
let fruits = ['Apple', 'Banana', 'Mango', 'Orange']
let removed = fruits.splice(2, 1);
// fruits is ['Apple', 'Banana', 'Orange']
// removed is ['Mango']
delete: delete anArray[index];
let fruits = ['Apple', 'Banana', 'Mango', 'Orange']
let removed = delete fruits(2);
// fruits is ['Apple', 'Banana', undefined, 'Orange']
// removed is true
Be careful when you use the delete for an array. It is good for deleting attributes of objects, but not so good for arrays. It is better to use splice for arrays.
Keep in mind that when you use delete for an array you could get wrong results for anArray.length. In other words, delete would remove the element, but it wouldn't update the value of the length property.
You can also expect to have holes in index numbers after using delete, e.g. you could end up with having indexes 1, 3, 4, 8, 9, and 11 and length as it was before using delete. In that case, all indexed for loops would crash, since indexes are no longer sequential.
If you are forced to use delete for some reason, then you should use for each loops when you need to loop through arrays. As the matter of fact, always avoid using indexed for loops, if possible. That way the code would be more robust and less prone to problems with indexes.
Array.prototype.removeByValue = function (val) {
for (var i = 0; i < this.length; i++) {
if (this[i] === val) {
this.splice(i, 1);
i--;
}
}
return this;
}
var fruits = ['apple', 'banana', 'carrot', 'orange'];
fruits.removeByValue('banana');
console.log(fruits);
// -> ['apple', 'carrot', 'orange']
There isn't any need to use indexOf or splice. However, it performs better if you only want to remove one occurrence of an element.
Find and move (move):
function move(arr, val) {
var j = 0;
for (var i = 0, l = arr.length; i < l; i++) {
if (arr[i] !== val) {
arr[j++] = arr[i];
}
}
arr.length = j;
}
Use indexOf and splice (indexof):
function indexof(arr, val) {
var i;
while ((i = arr.indexOf(val)) != -1) {
arr.splice(i, 1);
}
}
Use only splice (splice):
function splice(arr, val) {
for (var i = arr.length; i--;) {
if (arr[i] === val) {
arr.splice(i, 1);
}
}
}
Run-times on Node.js for an array with 1000 elements (averaged over 10,000 runs):
indexof is approximately 10 times slower than move. Even if improved by removing the call to indexOf in splice, it performs much worse than move.
Remove all occurrences:
move 0.0048 ms
indexof 0.0463 ms
splice 0.0359 ms
Remove first occurrence:
move_one 0.0041 ms
indexof_one 0.0021 ms
This provides a predicate instead of a value.
NOTE: it will update the given array, and return the affected rows.
Usage
var removed = helper.remove(arr, row => row.id === 5 );
var removed = helper.removeAll(arr, row => row.name.startsWith('BMW'));
Definition
var helper = {
// Remove and return the first occurrence
remove: function(array, predicate) {
for (var i = 0; i < array.length; i++) {
if (predicate(array[i])) {
return array.splice(i, 1);
}
}
},
// Remove and return all occurrences
removeAll: function(array, predicate) {
var removed = [];
for (var i = 0; i < array.length; ) {
if (predicate(array[i])) {
removed.push(array.splice(i, 1));
continue;
}
i++;
}
return removed;
},
};
You can do it easily with the filter method:
function remove(arrOriginal, elementToRemove){
return arrOriginal.filter(function(el){return el !== elementToRemove});
}
console.log(remove([1, 2, 1, 0, 3, 1, 4], 1));
This removes all elements from the array and also works faster than a combination of slice and indexOf.
Using filter is an elegant way to achieve this requirement.
filter will not mutate the original array.
const num = 3;
let arr = [1, 2, 3, 4];
const arr2 = arr.filter(x => x !== num);
console.log(arr); // [1, 2, 3, 4]
console.log(arr2); // [1, 2, 4]
You can use filter and then assign the result to the original array if you want to achieve a mutation removal behaviour.
const num = 3;
let arr = [1, 2, 3, 4];
arr = arr.filter(x => x !== num);
console.log(arr); // [1, 2, 4]
By the way, filter will remove all of the occurrences matched in the condition (not just the first occurrence) like you can see in the following example
const num = 3;
let arr = [1, 2, 3, 3, 3, 4];
arr = arr.filter(x => x !== num);
console.log(arr); // [1, 2, 4]
In case, you just want to remove the first occurrence, you can use the splice method
const num = 3;
let arr = [1, 2, 3, 3, 3, 4];
const idx = arr.indexOf(num);
arr.splice(idx, idx !== -1 ? 1 : 0);
console.log(arr); // [1, 2, 3, 3, 4]
John Resig posted a good implementation:
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
If you don’t want to extend a global object, you can do something like the following, instead:
// Array Remove - By John Resig (MIT Licensed)
Array.remove = function(array, from, to) {
var rest = array.slice((to || from) + 1 || array.length);
array.length = from < 0 ? array.length + from : from;
return array.push.apply(array, rest);
};
But the main reason I am posting this is to warn users against the alternative implementation suggested in the comments on that page (Dec 14, 2007):
Array.prototype.remove = function(from, to) {
this.splice(from, (to=[0, from || 1, ++to - from][arguments.length]) < 0 ? this.length + to : to);
return this.length;
};
It seems to work well at first, but through a painful process I discovered it fails when trying to remove the second to last element in an array. For example, if you have a 10-element array and you try to remove the 9th element with this:
myArray.remove(8);
You end up with an 8-element array. I don't know why, but I confirmed John's original implementation doesn't have this problem.
You can use ES6. For example to delete the value '3' in this case:
var array=['1','2','3','4','5','6']
var newArray = array.filter((value)=>value!='3');
console.log(newArray);
Output :
["1", "2", "4", "5", "6"]
Underscore.js can be used to solve issues with multiple browsers. It uses in-build browser methods if present. If they are absent like in the case of older Internet Explorer versions it uses its own custom methods.
A simple example to remove elements from array (from the website):
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); // => [2, 3, 4]
If you want a new array with the deleted positions removed, you can always delete the specific element and filter out the array. It might need an extension of the array object for browsers that don't implement the filter method, but in the long term it's easier since all you do is this:
var my_array = [1, 2, 3, 4, 5, 6];
delete my_array[4];
console.log(my_array.filter(function(a){return typeof a !== 'undefined';}));
It should display [1, 2, 3, 4, 6].
Here are a few ways to remove an item from an array using JavaScript.
All the method described do not mutate the original array, and instead create a new one.
If you know the index of an item
Suppose you have an array, and you want to remove an item in position i.
One method is to use slice():
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const i = 3
const filteredItems = items.slice(0, i).concat(items.slice(i+1, items.length))
console.log(filteredItems)
slice() creates a new array with the indexes it receives. We simply create a new array, from start to the index we want to remove, and concatenate another array from the first position following the one we removed to the end of the array.
If you know the value
In this case, one good option is to use filter(), which offers a more declarative approach:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(item => item !== valueToRemove)
console.log(filteredItems)
This uses the ES6 arrow functions. You can use the traditional functions to support older browsers:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(function(item) {
return item !== valueToRemove
})
console.log(filteredItems)
or you can use Babel and transpile the ES6 code back to ES5 to make it more digestible to old browsers, yet write modern JavaScript in your code.
Removing multiple items
What if instead of a single item, you want to remove many items?
Let's find the simplest solution.
By index
You can just create a function and remove items in series:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const removeItem = (items, i) =>
items.slice(0, i-1).concat(items.slice(i, items.length))
let filteredItems = removeItem(items, 3)
filteredItems = removeItem(filteredItems, 5)
//["a", "b", "c", "d"]
console.log(filteredItems)
By value
You can search for inclusion inside the callback function:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valuesToRemove = ['c', 'd']
const filteredItems = items.filter(item => !valuesToRemove.includes(item))
// ["a", "b", "e", "f"]
console.log(filteredItems)
Avoid mutating the original array
splice() (not to be confused with slice()) mutates the original array, and should be avoided.
(originally posted on my site https://flaviocopes.com/how-to-remove-item-from-array/)
Check out this code. It works in every major browser.
remove_item = function(arr, value) {
var b = '';
for (b in arr) {
if (arr[b] === value) {
arr.splice(b, 1);
break;
}
}
return arr;
};
var array = [1,3,5,6,5,9,5,3,55]
var res = remove_item(array,5);
console.log(res)
Removing a particular element/string from an array can be done in a one-liner:
theArray.splice(theArray.indexOf("stringToRemoveFromArray"), 1);
where:
theArray: the array you want to remove something particular from
stringToRemoveFromArray: the string you want to be removed and 1 is the number of elements you want to remove.
NOTE: If "stringToRemoveFromArray" is not located in the array, this will remove the last element of the array.
It's always good practice to check if the element exists in your array first, before removing it.
if (theArray.indexOf("stringToRemoveFromArray") >= 0){
theArray.splice(theArray.indexOf("stringToRemoveFromArray"), 1);
}
Depending if you have newer or older version of Ecmascript running on your client's computers:
var array=['1','2','3','4','5','6']
var newArray = array.filter((value)=>value!='3');
OR
var array = ['1','2','3','4','5','6'];
var newArray = array.filter(function(item){ return item !== '3' });
Where '3' is the value you want to be removed from the array.
The array would then become : ['1','2','4','5','6']
ES10
This post summarizes common approaches to element removal from an array as of ECMAScript 2019 (ES10).
1. General cases
1.1. Removing Array element by value using .splice()
| In-place: Yes |
| Removes duplicates: Yes(loop), No(indexOf) |
| By value / index: By index |
If you know the value you want to remove from an array you can use the splice method. First, you must identify the index of the target item. You then use the index as the start element and remove just one element.
// With a 'for' loop
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
for( let i = 0; i < arr.length; i++){
if ( arr[i] === 5) {
arr.splice(i, 1);
}
} // => [1, 2, 3, 4, 6, 7, 8, 9, 0]
// With the .indexOf() method
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
const i = arr.indexOf(5);
arr.splice(i, 1); // => [1, 2, 3, 4, 6, 7, 8, 9, 0]
1.2. Removing Array element using the .filter() method
| In-place: No |
| Removes duplicates: Yes |
| By value / index: By value |
The specific element can be filtered out from the array, by providing a filtering function. Such function is then called for every element in the array.
const value = 3
let arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(item => item !== value)
console.log(arr)
// [ 1, 2, 4, 5 ]
1.3. Removing Array element by extending Array.prototype
| In-place: Yes/No (Depends on implementation) |
| Removes duplicates: Yes/No (Depends on implementation) |
| By value / index: By index / By value (Depends on implementation) |
The prototype of Array can be extended with additional methods. Such methods will be then available to use on created arrays.
Note: Extending prototypes of objects from the standard library of JavaScript (like Array) is considered by some as an antipattern.
// In-place, removes all, by value implementation
Array.prototype.remove = function(item) {
for (let i = 0; i < this.length; i++) {
if (this[i] === item) {
this.splice(i, 1);
}
}
}
const arr1 = [1,2,3,1];
arr1.remove(1) // arr1 equals [2,3]
// Non-stationary, removes first, by value implementation
Array.prototype.remove = function(item) {
const arr = this.slice();
for (let i = 0; i < this.length; i++) {
if (arr[i] === item) {
arr.splice(i, 1);
return arr;
}
}
return arr;
}
let arr2 = [1,2,3,1];
arr2 = arr2.remove(1) // arr2 equals [2,3,1]
1.4. Removing Array element using the delete operator
| In-place: Yes |
| Removes duplicates: No |
| By value / index: By index |
Using the delete operator does not affect the length property. Nor does it affect the indexes of subsequent elements. The array becomes sparse, which is a fancy way of saying the deleted item is not removed but becomes undefined.
const arr = [1, 2, 3, 4, 5, 6];
delete arr[4]; // Delete element with index 4
console.log( arr ); // [1, 2, 3, 4, undefined, 6]
The delete operator is designed to remove properties from JavaScript objects, which arrays are objects.
1.5. Removing Array element using Object utilities (>= ES10)
| In-place: No |
| Removes duplicates: Yes |
| By value / index: By value |
ES10 introduced Object.fromEntries, which can be used to create the desired Array from any Array-like object and filter unwanted elements during the process.
const object = [1,2,3,4];
const valueToRemove = 3;
const arr = Object.values(Object.fromEntries(
Object.entries(object)
.filter(([ key, val ]) => val !== valueToRemove)
));
console.log(arr); // [1,2,4]
2. Special cases
2.1 Removing element if it's at the end of the Array
2.1.1. Changing Array length
| In-place: Yes |
| Removes duplicates: No |
| By value / index: N/A |
JavaScript Array elements can be removed from the end of an array by setting the length property to a value less than the current value. Any element whose index is greater than or equal to the new length will be removed.
const arr = [1, 2, 3, 4, 5, 6];
arr.length = 5; // Set length to remove element
console.log( arr ); // [1, 2, 3, 4, 5]
2.1.2. Using .pop() method
| In-place: Yes |
| Removes duplicates: No |
| By value / index: N/A |
The pop method removes the last element of the array, returns that element, and updates the length property. The pop method modifies the array on which it is invoked, This means unlike using delete the last element is removed completely and the array length reduced.
const arr = [1, 2, 3, 4, 5, 6];
arr.pop(); // returns 6
console.log( arr ); // [1, 2, 3, 4, 5]
2.2. Removing element if it's at the beginning of the Array
| In-place: Yes |
| Removes duplicates: No |
| By value / index: N/A |
The .shift() method works much like the pop method except it removes the first element of a JavaScript array instead of the last. When the element is removed the remaining elements are shifted down.
const arr = [1, 2, 3, 4];
arr.shift(); // returns 1
console.log( arr ); // [2, 3, 4]
2.3. Removing element if it's the only element in the Array
| In-place: Yes |
| Removes duplicates: N/A |
| By value / index: N/A |
The fastest technique is to set an array variable to an empty array.
let arr = [1];
arr = []; //empty array
Alternatively technique from 2.1.1 can be used by setting length to 0.
You can use lodash _.pull (mutate array), _.pullAt (mutate array) or _.without (does't mutate array),
var array1 = ['a', 'b', 'c', 'd']
_.pull(array1, 'c')
console.log(array1) // ['a', 'b', 'd']
var array2 = ['e', 'f', 'g', 'h']
_.pullAt(array2, 0)
console.log(array2) // ['f', 'g', 'h']
var array3 = ['i', 'j', 'k', 'l']
var newArray = _.without(array3, 'i') // ['j', 'k', 'l']
console.log(array3) // ['i', 'j', 'k', 'l']
ES6 & without mutation: (October 2016)
const removeByIndex = (list, index) =>
[
...list.slice(0, index),
...list.slice(index + 1)
];
output = removeByIndex([33,22,11,44],1) //=> [33,11,44]
console.log(output)
Performance
Today (2019-12-09) I conduct performance tests on macOS v10.13.6 (High Sierra) for chosen solutions. I show delete (A), but I do not use it in comparison with other methods, because it left empty space in the array.
The conclusions
the fastest solution is array.splice (C) (except Safari for small arrays where it has the second time)
for big arrays, array.slice+splice (H) is the fastest immutable solution for Firefox and Safari; Array.from (B) is fastest in Chrome
mutable solutions are usually 1.5x-6x faster than immutable
for small tables on Safari, surprisingly the mutable solution (C) is slower than the immutable solution (G)
Details
In tests, I remove the middle element from the array in different ways. The A, C solutions are in-place. The B, D, E, F, G, H solutions are immutable.
Results for an array with 10 elements
In Chrome the array.splice (C) is the fastest in-place solution. The array.filter (D) is the fastest immutable solution. The slowest is array.slice (F). You can perform the test on your machine here.
Results for an array with 1.000.000 elements
In Chrome the array.splice (C) is the fastest in-place solution (the delete (C) is similar fast - but it left an empty slot in the array (so it does not perform a 'full remove')). The array.slice-splice (H) is the fastest immutable solution. The slowest is array.filter (D and E). You can perform the test on your machine here.
var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var log = (letter,array) => console.log(letter, array.join `,`);
function A(array) {
var index = array.indexOf(5);
delete array[index];
log('A', array);
}
function B(array) {
var index = array.indexOf(5);
var arr = Array.from(array);
arr.splice(index, 1)
log('B', arr);
}
function C(array) {
var index = array.indexOf(5);
array.splice(index, 1);
log('C', array);
}
function D(array) {
var arr = array.filter(item => item !== 5)
log('D', arr);
}
function E(array) {
var index = array.indexOf(5);
var arr = array.filter((item, i) => i !== index)
log('E', arr);
}
function F(array) {
var index = array.indexOf(5);
var arr = array.slice(0, index).concat(array.slice(index + 1))
log('F', arr);
}
function G(array) {
var index = array.indexOf(5);
var arr = [...array.slice(0, index), ...array.slice(index + 1)]
log('G', arr);
}
function H(array) {
var index = array.indexOf(5);
var arr = array.slice(0);
arr.splice(index, 1);
log('H', arr);
}
A([...a]);
B([...a]);
C([...a]);
D([...a]);
E([...a]);
F([...a]);
G([...a]);
H([...a]);
This snippet only presents code used in performance tests - it does not perform tests itself.
Comparison for browsers: Chrome v78.0.0, Safari v13.0.4, and Firefox v71.0.0
OK, for example you have the array below:
var num = [1, 2, 3, 4, 5];
And we want to delete number 4. You can simply use the below code:
num.splice(num.indexOf(4), 1); // num will be [1, 2, 3, 5];
If you are reusing this function, you write a reusable function which will be attached to the native array function like below:
Array.prototype.remove = Array.prototype.remove || function(x) {
const i = this.indexOf(x);
if(i===-1)
return;
this.splice(i, 1); // num.remove(5) === [1, 2, 3];
}
But how about if you have the below array instead with a few [5]s in the array?
var num = [5, 6, 5, 4, 5, 1, 5];
We need a loop to check them all, but an easier and more efficient way is using built-in JavaScript functions, so we write a function which use a filter like below instead:
const _removeValue = (arr, x) => arr.filter(n => n!==x);
//_removeValue([1, 2, 3, 4, 5, 5, 6, 5], 5) // Return [1, 2, 3, 4, 6]
Also there are third-party libraries which do help you to do this, like Lodash or Underscore. For more information, look at lodash _.pull, _.pullAt or _.without.
I'm pretty new to JavaScript and needed this functionality. I merely wrote this:
function removeFromArray(array, item, index) {
while((index = array.indexOf(item)) > -1) {
array.splice(index, 1);
}
}
Then when I want to use it:
//Set-up some dummy data
var dummyObj = {name:"meow"};
var dummyArray = [dummyObj, "item1", "item1", "item2"];
//Remove the dummy data
removeFromArray(dummyArray, dummyObj);
removeFromArray(dummyArray, "item2");
Output - As expected.
["item1", "item1"]
You may have different needs than I, so you can easily modify it to suit them. I hope this helps someone.
I want to answer based on ECMAScript 6. Assume you have an array like below:
let arr = [1,2,3,4];
If you want to delete at a special index like 2, write the below code:
arr.splice(2, 1); //=> arr became [1,2,4]
But if you want to delete a special item like 3 and you don't know its index, do like below:
arr = arr.filter(e => e !== 3); //=> arr became [1,2,4]
Hint: please use an arrow function for filter callback unless you will get an empty array.
If you have complex objects in the array you can use filters?
In situations where $.inArray or array.splice is not as easy to use. Especially if the objects are perhaps shallow in the array.
E.g. if you have an object with an Id field and you want the object removed from an array:
this.array = this.array.filter(function(element, i) {
return element.id !== idToRemove;
});
Update: This method is recommended only if you cannot use ECMAScript 2015 (formerly known as ES6). If you can use it, other answers here provide much neater implementations.
This gist here will solve your problem, and also deletes all occurrences of the argument instead of just 1 (or a specified value).
Array.prototype.destroy = function(obj){
// Return null if no objects were found and removed
var destroyed = null;
for(var i = 0; i < this.length; i++){
// Use while-loop to find adjacent equal objects
while(this[i] === obj){
// Remove this[i] and store it within destroyed
destroyed = this.splice(i, 1)[0];
}
}
return destroyed;
}
Usage:
var x = [1, 2, 3, 3, true, false, undefined, false];
x.destroy(3); // => 3
x.destroy(false); // => false
x; // => [1, 2, true, undefined]
x.destroy(true); // => true
x.destroy(undefined); // => undefined
x; // => [1, 2]
x.destroy(3); // => null
x; // => [1, 2]
You should never mutate your array as this is against the functional programming pattern. You can create a new array without referencing the one you want to change data of using the ECMAScript 6 method filter;
var myArray = [1, 2, 3, 4, 5, 6];
Suppose you want to remove 5 from the array, you can simply do it like this:
myArray = myArray.filter(value => value !== 5);
This will give you a new array without the value you wanted to remove. So the result will be:
[1, 2, 3, 4, 6]; // 5 has been removed from this array
For further understanding you can read the MDN documentation on Array.filter.
A more modern, ECMAScript 2015 (formerly known as Harmony or ES 6) approach. Given:
const items = [1, 2, 3, 4];
const index = 2;
Then:
items.filter((x, i) => i !== index);
Yielding:
[1, 2, 4]
You can use Babel and a polyfill service to ensure this is well supported across browsers.
You can do a backward loop to make sure not to screw up the indexes, if there are multiple instances of the element.
var myElement = "chocolate";
var myArray = ['chocolate', 'poptart', 'poptart', 'poptart', 'chocolate', 'poptart', 'poptart', 'chocolate'];
/* Important code */
for (var i = myArray.length - 1; i >= 0; i--) {
if (myArray[i] == myElement) myArray.splice(i, 1);
}
console.log(myArray);

Terse way to intersperse element between all elements in JavaScript array?

Say I have an array var arr = [1, 2, 3], and I want to separate each element by an element eg. var sep = "&", so the output is [1, "&", 2, "&", 3].
Another way to think about it is I want to do Array.prototype.join (arr.join(sep)) without the result being a string (because the elements and separator I am trying to use are Objects, not strings).
Is there a functional/nice/elegant way to do this in either es6/7 or lodash without something that feels clunky like:
_.flatten(arr.map((el, i) => [el, i < arr.length-1 ? sep : null])) // too complex
or
_.flatten(arr.map(el => [el, sep]).slice(0,-1) // extra sep added, memory wasted
or even
arr.reduce((prev,curr) => { prev.push(curr, sep); return prev; }, []).slice(0,-1)
// probably the best out of the three, but I have to do a map already
// and I still have the same problem as the previous two - either
// inline ternary or slice
Edit: Haskell has this function, called intersperse
Using a generator:
function *intersperse(a, delim) {
let first = true;
for (const x of a) {
if (!first) yield delim;
first = false;
yield x;
}
}
console.log([...intersperse(array, '&')]);
Thanks to #Bergi for pointing out the useful generalization that the input could be any iterable.
If you don't like using generators, then
[].concat(...a.map(e => ['&', e])).slice(1)
A spread and explicit return in reducing function will make it more terse:
const intersperse = (arr, sep) => arr.reduce((a,v)=>[...a,v,sep],[]).slice(0,-1)
// intersperse([1,2,3], 'z')
// [1, "z", 2, "z", 3]
In ES6, you'd write a generator function that can produce an iterator which yields the input with the interspersed elements:
function* intersperse(iterable, separator) {
const iterator = iterable[Symbol.iterator]();
const first = iterator.next();
if (first.done) return;
else yield first.value;
for (const value of iterator) {
yield separator;
yield value;
}
}
console.log(Array.from(intersperse([1, 2, 3], "&")));
One straightforward approach could be like feeding the reduce function with an initial array in size one less than the double of our original array, filled with the character to be used for interspersing. Then mapping the elements of the original array at index i to 2*i in the initially fed target array would do the job perfectly..
In this approach i don't see (m)any redundant operations. Also since we are not modifying any of the array sizes after they are set, i wouldn't expect any background tasks to run for memory reallocation, optimization etc.
One other good part is using the standard array methods since they check all kinds of mismatch and whatnot.
This function returns a new array, in which the called upon array's items are interspersed with the provided argument.
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
Array.prototype.intersperse = function(s){
return this.reduce((p,c,i) => (p[2*i]=c,p), new Array(2*this.length-1).fill(s));
}
document.write("<pre>" + JSON.stringify(arr.intersperse("&")) + "</pre>");
Using reduce but without slice
var arr = ['a','b','c','d'];
var lastIndex = arr.length-1;
arr.reduce((res,x,index)=>{
res.push(x);
if(lastIndex !== index)
res.push('&');
return res;
},[]);
If you have Ramda in your dependencies or if willing to add it, there is intersperse method there.
From the docs:
Creates a new list with the separator interposed between elements.
Dispatches to the intersperse method of the second argument, if present.
R.intersperse('n', ['ba', 'a', 'a']); //=> ['ba', 'n', 'a', 'n', 'a']
Or you can check out the source for one of the ways to do it in your codebase. https://github.com/ramda/ramda/blob/v0.24.1/src/intersperse.js
You could use Array.from to create an array with the final size, and then use the callback argument to actually populate it:
const intersperse = (arr, sep) => Array.from(
{ length: Math.max(0, arr.length * 2 - 1) },
(_, i) => i % 2 ? sep : arr[i >> 1]
);
// Demo:
let res = intersperse([1, 2, 3], "&");
console.log(res);
ONE-LINER and FAST
const intersperse = (ar,s)=>[...Array(2*ar.length-1)].map((_,i)=>i%2?s:ar[i/2]);
console.log(intersperse([1, 2, 3], '&'));
javascript has a method join() and split()
var arr = ['a','b','c','d'];
arr = arr.join('&');
document.writeln(arr);
Output should be: a&b&c&d
now split again:
arr = arr.split("");
arr is now:
arr = ['a','&','b','&','c','&','d'];
if (!Array.prototype.intersperse) {
Object.defineProperty(Array.prototype, 'intersperse', {
value: function(something) {
if (this === null) {
throw new TypeError( 'Array.prototype.intersperse ' +
'called on null or undefined' );
}
var isFunc = (typeof something == 'function')
return this.concat.apply([],
this.map(function(e,i) {
return i ? [isFunc ? something(this[i-1]) : something, e] : [e] }.bind(this)))
}
});
}
you can also use the following:
var arr =['a', 'b', 'c', 'd'];
arr.forEach(function(element, index, array){
array.splice(2*index+1, 0, '&');
});
arr.pop();
My take:
const _ = require('lodash');
_.mixin({
intersperse(array, sep) {
return _(array)
.flatMap(x => [x, sep])
.take(2 * array.length - 1)
.value();
},
});
// _.intersperse(["a", "b", "c"], "-")
// > ["a", "-", "b", "-", "c"]
const arr = [1, 2, 3];
function intersperse(items, separator) {
const result = items.reduce(
(res, el) => [...res, el, separator], []);
result.pop();
return result;
}
console.log(intersperse(arr, '&'));
A few years later, here's a recursive generator solution. Enjoy!
const intersperse = function *([first, ...rest], delim){
yield first;
if(!rest.length){
return;
}
yield delim;
yield * intersperse(rest, delim);
};
console.log([...intersperse(array, '&')]);
export const intersperse = (array, insertSeparator) => {
if (!isArray(array)) {
throw new Error(`Wrong argument in intersperse function, expected array, got ${typeof array}`);
}
if (!isFunction(insertSeparator)) {
throw new Error(`Wrong argument in intersperse function, expected function, got ${typeof insertSeparator}`);
}
return flatMap(
array,
(item, index) => index > 0 ? [insertSeparator(item, index), item] : [item] // eslint-disable-line no-confusing-arrow
);
};
Here is also a version with reduce only:
const intersperse = (xs, s) => xs.reduce((acc, x) => acc ? [...acc, s, x] : [x], null)
const a = [1, 2, 3, 4, 5]
console.log(intersperse(a, 0))
// [1, 0, 2, 0, 3, 0, 4, 0, 5]
Updated for objects not using join method:
for (var i=0;i<arr.length;i++;) {
newarr.push(arr[i]);
if(i>0) {
newarr.push('&');
}
}
newarr should be:
newarr = ['a','&','b','&','c','&','d'];

How can I remove a specific item from an array in JavaScript?

How do I remove a specific value from an array? Something like:
array.remove(value);
Constraints: I have to use core JavaScript. Frameworks are not allowed.
Find the index of the array element you want to remove using indexOf, and then remove that index with splice.
The splice() method changes the contents of an array by removing
existing elements and/or adding new elements.
const array = [2, 5, 9];
console.log(array);
const index = array.indexOf(5);
if (index > -1) { // only splice array when item is found
array.splice(index, 1); // 2nd parameter means remove one item only
}
// array = [2, 9]
console.log(array);
The second parameter of splice is the number of elements to remove. Note that splice modifies the array in place and returns a new array containing the elements that have been removed.
For the reason of completeness, here are functions. The first function removes only a single occurrence (i.e. removing the first match of 5 from [2,5,9,1,5,8,5]), while the second function removes all occurrences:
function removeItemOnce(arr, value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
function removeItemAll(arr, value) {
var i = 0;
while (i < arr.length) {
if (arr[i] === value) {
arr.splice(i, 1);
} else {
++i;
}
}
return arr;
}
// Usage
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
console.log(removeItemAll([2,5,9,1,5,8,5], 5))
In TypeScript, these functions can stay type-safe with a type parameter:
function removeItem<T>(arr: Array<T>, value: T): Array<T> {
const index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
Edited on 2016 October
Do it simple, intuitive and explicit (Occam's razor)
Do it immutable (original array stays unchanged)
Do it with standard JavaScript functions, if your browser doesn't support them - use polyfill
In this code example I use array.filter(...) function to remove unwanted items from an array. This function doesn't change the original array and creates a new one. If your browser doesn't support this function (e.g. Internet Explorer before version 9, or Firefox before version 1.5), consider polyfilling with core-js.
Removing item (ECMA-262 Edition 5 code AKA old style JavaScript)
var value = 3
var arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(function(item) {
return item !== value
})
console.log(arr)
// [ 1, 2, 4, 5 ]
Removing item (ECMAScript 6 code)
let value = 3
let arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(item => item !== value)
console.log(arr)
// [ 1, 2, 4, 5 ]
IMPORTANT ECMAScript 6 () => {} arrow function syntax is not supported in Internet Explorer at all, Chrome before version 45, Firefox before version 22, and Safari before version 10. To use ECMAScript 6 syntax in old browsers you can use BabelJS.
Removing multiple items (ECMAScript 7 code)
An additional advantage of this method is that you can remove multiple items
let forDeletion = [2, 3, 5]
let arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(item => !forDeletion.includes(item))
// !!! Read below about array.includes(...) support !!!
console.log(arr)
// [ 1, 4 ]
IMPORTANT array.includes(...) function is not supported in Internet Explorer at all, Chrome before version 47, Firefox before version 43, Safari before version 9, and Edge before version 14 but you can polyfill with core-js.
Removing multiple items (in the future, maybe)
If the "This-Binding Syntax" proposal is ever accepted, you'll be able to do this:
// array-lib.js
export function remove(...forDeletion) {
return this.filter(item => !forDeletion.includes(item))
}
// main.js
import { remove } from './array-lib.js'
let arr = [1, 2, 3, 4, 5, 3]
// :: This-Binding Syntax Proposal
// using "remove" function as "virtual method"
// without extending Array.prototype
arr = arr::remove(2, 3, 5)
console.log(arr)
// [ 1, 4 ]
Try it yourself in BabelJS :)
Reference
Array.prototype.includes
Functional composition
I don't know how you are expecting array.remove(int) to behave. There are three possibilities I can think of that you might want.
To remove an element of an array at an index i:
array.splice(i, 1);
If you want to remove every element with value number from the array:
for (var i = array.length - 1; i >= 0; i--) {
if (array[i] === number) {
array.splice(i, 1);
}
}
If you just want to make the element at index i no longer exist, but you don't want the indexes of the other elements to change:
delete array[i];
It depends on whether you want to keep an empty spot or not.
If you do want an empty slot:
array[index] = undefined;
If you don't want an empty slot:
//To keep the original:
//oldArray = [...array];
//This modifies the array.
array.splice(index, 1);
And if you need the value of that item, you can just store the returned array's element:
var value = array.splice(index, 1)[0];
If you want to remove at either end of the array, you can use array.pop() for the last one or array.shift() for the first one (both return the value of the item as well).
If you don't know the index of the item, you can use array.indexOf(item) to get it (in a if() to get one item or in a while() to get all of them). array.indexOf(item) returns either the index or -1 if not found.
A friend was having issues in Internet Explorer 8 and showed me what he did. I told him it was wrong, and he told me he got the answer here. The current top answer will not work in all browsers (Internet Explorer 8 for example), and it will only remove the first occurrence of the item.
Remove ALL instances from an array
function removeAllInstances(arr, item) {
for (var i = arr.length; i--;) {
if (arr[i] === item) arr.splice(i, 1);
}
}
It loops through the array backwards (since indices and length will change as items are removed) and removes the item if it's found. It works in all browsers.
There are two major approaches
splice(): anArray.splice(index, 1);
let fruits = ['Apple', 'Banana', 'Mango', 'Orange']
let removed = fruits.splice(2, 1);
// fruits is ['Apple', 'Banana', 'Orange']
// removed is ['Mango']
delete: delete anArray[index];
let fruits = ['Apple', 'Banana', 'Mango', 'Orange']
let removed = delete fruits(2);
// fruits is ['Apple', 'Banana', undefined, 'Orange']
// removed is true
Be careful when you use the delete for an array. It is good for deleting attributes of objects, but not so good for arrays. It is better to use splice for arrays.
Keep in mind that when you use delete for an array you could get wrong results for anArray.length. In other words, delete would remove the element, but it wouldn't update the value of the length property.
You can also expect to have holes in index numbers after using delete, e.g. you could end up with having indexes 1, 3, 4, 8, 9, and 11 and length as it was before using delete. In that case, all indexed for loops would crash, since indexes are no longer sequential.
If you are forced to use delete for some reason, then you should use for each loops when you need to loop through arrays. As the matter of fact, always avoid using indexed for loops, if possible. That way the code would be more robust and less prone to problems with indexes.
Array.prototype.removeByValue = function (val) {
for (var i = 0; i < this.length; i++) {
if (this[i] === val) {
this.splice(i, 1);
i--;
}
}
return this;
}
var fruits = ['apple', 'banana', 'carrot', 'orange'];
fruits.removeByValue('banana');
console.log(fruits);
// -> ['apple', 'carrot', 'orange']
There isn't any need to use indexOf or splice. However, it performs better if you only want to remove one occurrence of an element.
Find and move (move):
function move(arr, val) {
var j = 0;
for (var i = 0, l = arr.length; i < l; i++) {
if (arr[i] !== val) {
arr[j++] = arr[i];
}
}
arr.length = j;
}
Use indexOf and splice (indexof):
function indexof(arr, val) {
var i;
while ((i = arr.indexOf(val)) != -1) {
arr.splice(i, 1);
}
}
Use only splice (splice):
function splice(arr, val) {
for (var i = arr.length; i--;) {
if (arr[i] === val) {
arr.splice(i, 1);
}
}
}
Run-times on Node.js for an array with 1000 elements (averaged over 10,000 runs):
indexof is approximately 10 times slower than move. Even if improved by removing the call to indexOf in splice, it performs much worse than move.
Remove all occurrences:
move 0.0048 ms
indexof 0.0463 ms
splice 0.0359 ms
Remove first occurrence:
move_one 0.0041 ms
indexof_one 0.0021 ms
This provides a predicate instead of a value.
NOTE: it will update the given array, and return the affected rows.
Usage
var removed = helper.remove(arr, row => row.id === 5 );
var removed = helper.removeAll(arr, row => row.name.startsWith('BMW'));
Definition
var helper = {
// Remove and return the first occurrence
remove: function(array, predicate) {
for (var i = 0; i < array.length; i++) {
if (predicate(array[i])) {
return array.splice(i, 1);
}
}
},
// Remove and return all occurrences
removeAll: function(array, predicate) {
var removed = [];
for (var i = 0; i < array.length; ) {
if (predicate(array[i])) {
removed.push(array.splice(i, 1));
continue;
}
i++;
}
return removed;
},
};
You can do it easily with the filter method:
function remove(arrOriginal, elementToRemove){
return arrOriginal.filter(function(el){return el !== elementToRemove});
}
console.log(remove([1, 2, 1, 0, 3, 1, 4], 1));
This removes all elements from the array and also works faster than a combination of slice and indexOf.
Using filter is an elegant way to achieve this requirement.
filter will not mutate the original array.
const num = 3;
let arr = [1, 2, 3, 4];
const arr2 = arr.filter(x => x !== num);
console.log(arr); // [1, 2, 3, 4]
console.log(arr2); // [1, 2, 4]
You can use filter and then assign the result to the original array if you want to achieve a mutation removal behaviour.
const num = 3;
let arr = [1, 2, 3, 4];
arr = arr.filter(x => x !== num);
console.log(arr); // [1, 2, 4]
By the way, filter will remove all of the occurrences matched in the condition (not just the first occurrence) like you can see in the following example
const num = 3;
let arr = [1, 2, 3, 3, 3, 4];
arr = arr.filter(x => x !== num);
console.log(arr); // [1, 2, 4]
In case, you just want to remove the first occurrence, you can use the splice method
const num = 3;
let arr = [1, 2, 3, 3, 3, 4];
const idx = arr.indexOf(num);
arr.splice(idx, idx !== -1 ? 1 : 0);
console.log(arr); // [1, 2, 3, 3, 4]
John Resig posted a good implementation:
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
If you don’t want to extend a global object, you can do something like the following, instead:
// Array Remove - By John Resig (MIT Licensed)
Array.remove = function(array, from, to) {
var rest = array.slice((to || from) + 1 || array.length);
array.length = from < 0 ? array.length + from : from;
return array.push.apply(array, rest);
};
But the main reason I am posting this is to warn users against the alternative implementation suggested in the comments on that page (Dec 14, 2007):
Array.prototype.remove = function(from, to) {
this.splice(from, (to=[0, from || 1, ++to - from][arguments.length]) < 0 ? this.length + to : to);
return this.length;
};
It seems to work well at first, but through a painful process I discovered it fails when trying to remove the second to last element in an array. For example, if you have a 10-element array and you try to remove the 9th element with this:
myArray.remove(8);
You end up with an 8-element array. I don't know why, but I confirmed John's original implementation doesn't have this problem.
You can use ES6. For example to delete the value '3' in this case:
var array=['1','2','3','4','5','6']
var newArray = array.filter((value)=>value!='3');
console.log(newArray);
Output :
["1", "2", "4", "5", "6"]
Underscore.js can be used to solve issues with multiple browsers. It uses in-build browser methods if present. If they are absent like in the case of older Internet Explorer versions it uses its own custom methods.
A simple example to remove elements from array (from the website):
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); // => [2, 3, 4]
If you want a new array with the deleted positions removed, you can always delete the specific element and filter out the array. It might need an extension of the array object for browsers that don't implement the filter method, but in the long term it's easier since all you do is this:
var my_array = [1, 2, 3, 4, 5, 6];
delete my_array[4];
console.log(my_array.filter(function(a){return typeof a !== 'undefined';}));
It should display [1, 2, 3, 4, 6].
Here are a few ways to remove an item from an array using JavaScript.
All the method described do not mutate the original array, and instead create a new one.
If you know the index of an item
Suppose you have an array, and you want to remove an item in position i.
One method is to use slice():
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const i = 3
const filteredItems = items.slice(0, i).concat(items.slice(i+1, items.length))
console.log(filteredItems)
slice() creates a new array with the indexes it receives. We simply create a new array, from start to the index we want to remove, and concatenate another array from the first position following the one we removed to the end of the array.
If you know the value
In this case, one good option is to use filter(), which offers a more declarative approach:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(item => item !== valueToRemove)
console.log(filteredItems)
This uses the ES6 arrow functions. You can use the traditional functions to support older browsers:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(function(item) {
return item !== valueToRemove
})
console.log(filteredItems)
or you can use Babel and transpile the ES6 code back to ES5 to make it more digestible to old browsers, yet write modern JavaScript in your code.
Removing multiple items
What if instead of a single item, you want to remove many items?
Let's find the simplest solution.
By index
You can just create a function and remove items in series:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const removeItem = (items, i) =>
items.slice(0, i-1).concat(items.slice(i, items.length))
let filteredItems = removeItem(items, 3)
filteredItems = removeItem(filteredItems, 5)
//["a", "b", "c", "d"]
console.log(filteredItems)
By value
You can search for inclusion inside the callback function:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valuesToRemove = ['c', 'd']
const filteredItems = items.filter(item => !valuesToRemove.includes(item))
// ["a", "b", "e", "f"]
console.log(filteredItems)
Avoid mutating the original array
splice() (not to be confused with slice()) mutates the original array, and should be avoided.
(originally posted on my site https://flaviocopes.com/how-to-remove-item-from-array/)
Check out this code. It works in every major browser.
remove_item = function(arr, value) {
var b = '';
for (b in arr) {
if (arr[b] === value) {
arr.splice(b, 1);
break;
}
}
return arr;
};
var array = [1,3,5,6,5,9,5,3,55]
var res = remove_item(array,5);
console.log(res)
Removing a particular element/string from an array can be done in a one-liner:
theArray.splice(theArray.indexOf("stringToRemoveFromArray"), 1);
where:
theArray: the array you want to remove something particular from
stringToRemoveFromArray: the string you want to be removed and 1 is the number of elements you want to remove.
NOTE: If "stringToRemoveFromArray" is not located in the array, this will remove the last element of the array.
It's always good practice to check if the element exists in your array first, before removing it.
if (theArray.indexOf("stringToRemoveFromArray") >= 0){
theArray.splice(theArray.indexOf("stringToRemoveFromArray"), 1);
}
Depending if you have newer or older version of Ecmascript running on your client's computers:
var array=['1','2','3','4','5','6']
var newArray = array.filter((value)=>value!='3');
OR
var array = ['1','2','3','4','5','6'];
var newArray = array.filter(function(item){ return item !== '3' });
Where '3' is the value you want to be removed from the array.
The array would then become : ['1','2','4','5','6']
ES10
This post summarizes common approaches to element removal from an array as of ECMAScript 2019 (ES10).
1. General cases
1.1. Removing Array element by value using .splice()
| In-place: Yes |
| Removes duplicates: Yes(loop), No(indexOf) |
| By value / index: By index |
If you know the value you want to remove from an array you can use the splice method. First, you must identify the index of the target item. You then use the index as the start element and remove just one element.
// With a 'for' loop
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
for( let i = 0; i < arr.length; i++){
if ( arr[i] === 5) {
arr.splice(i, 1);
}
} // => [1, 2, 3, 4, 6, 7, 8, 9, 0]
// With the .indexOf() method
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
const i = arr.indexOf(5);
arr.splice(i, 1); // => [1, 2, 3, 4, 6, 7, 8, 9, 0]
1.2. Removing Array element using the .filter() method
| In-place: No |
| Removes duplicates: Yes |
| By value / index: By value |
The specific element can be filtered out from the array, by providing a filtering function. Such function is then called for every element in the array.
const value = 3
let arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(item => item !== value)
console.log(arr)
// [ 1, 2, 4, 5 ]
1.3. Removing Array element by extending Array.prototype
| In-place: Yes/No (Depends on implementation) |
| Removes duplicates: Yes/No (Depends on implementation) |
| By value / index: By index / By value (Depends on implementation) |
The prototype of Array can be extended with additional methods. Such methods will be then available to use on created arrays.
Note: Extending prototypes of objects from the standard library of JavaScript (like Array) is considered by some as an antipattern.
// In-place, removes all, by value implementation
Array.prototype.remove = function(item) {
for (let i = 0; i < this.length; i++) {
if (this[i] === item) {
this.splice(i, 1);
}
}
}
const arr1 = [1,2,3,1];
arr1.remove(1) // arr1 equals [2,3]
// Non-stationary, removes first, by value implementation
Array.prototype.remove = function(item) {
const arr = this.slice();
for (let i = 0; i < this.length; i++) {
if (arr[i] === item) {
arr.splice(i, 1);
return arr;
}
}
return arr;
}
let arr2 = [1,2,3,1];
arr2 = arr2.remove(1) // arr2 equals [2,3,1]
1.4. Removing Array element using the delete operator
| In-place: Yes |
| Removes duplicates: No |
| By value / index: By index |
Using the delete operator does not affect the length property. Nor does it affect the indexes of subsequent elements. The array becomes sparse, which is a fancy way of saying the deleted item is not removed but becomes undefined.
const arr = [1, 2, 3, 4, 5, 6];
delete arr[4]; // Delete element with index 4
console.log( arr ); // [1, 2, 3, 4, undefined, 6]
The delete operator is designed to remove properties from JavaScript objects, which arrays are objects.
1.5. Removing Array element using Object utilities (>= ES10)
| In-place: No |
| Removes duplicates: Yes |
| By value / index: By value |
ES10 introduced Object.fromEntries, which can be used to create the desired Array from any Array-like object and filter unwanted elements during the process.
const object = [1,2,3,4];
const valueToRemove = 3;
const arr = Object.values(Object.fromEntries(
Object.entries(object)
.filter(([ key, val ]) => val !== valueToRemove)
));
console.log(arr); // [1,2,4]
2. Special cases
2.1 Removing element if it's at the end of the Array
2.1.1. Changing Array length
| In-place: Yes |
| Removes duplicates: No |
| By value / index: N/A |
JavaScript Array elements can be removed from the end of an array by setting the length property to a value less than the current value. Any element whose index is greater than or equal to the new length will be removed.
const arr = [1, 2, 3, 4, 5, 6];
arr.length = 5; // Set length to remove element
console.log( arr ); // [1, 2, 3, 4, 5]
2.1.2. Using .pop() method
| In-place: Yes |
| Removes duplicates: No |
| By value / index: N/A |
The pop method removes the last element of the array, returns that element, and updates the length property. The pop method modifies the array on which it is invoked, This means unlike using delete the last element is removed completely and the array length reduced.
const arr = [1, 2, 3, 4, 5, 6];
arr.pop(); // returns 6
console.log( arr ); // [1, 2, 3, 4, 5]
2.2. Removing element if it's at the beginning of the Array
| In-place: Yes |
| Removes duplicates: No |
| By value / index: N/A |
The .shift() method works much like the pop method except it removes the first element of a JavaScript array instead of the last. When the element is removed the remaining elements are shifted down.
const arr = [1, 2, 3, 4];
arr.shift(); // returns 1
console.log( arr ); // [2, 3, 4]
2.3. Removing element if it's the only element in the Array
| In-place: Yes |
| Removes duplicates: N/A |
| By value / index: N/A |
The fastest technique is to set an array variable to an empty array.
let arr = [1];
arr = []; //empty array
Alternatively technique from 2.1.1 can be used by setting length to 0.
You can use lodash _.pull (mutate array), _.pullAt (mutate array) or _.without (does't mutate array),
var array1 = ['a', 'b', 'c', 'd']
_.pull(array1, 'c')
console.log(array1) // ['a', 'b', 'd']
var array2 = ['e', 'f', 'g', 'h']
_.pullAt(array2, 0)
console.log(array2) // ['f', 'g', 'h']
var array3 = ['i', 'j', 'k', 'l']
var newArray = _.without(array3, 'i') // ['j', 'k', 'l']
console.log(array3) // ['i', 'j', 'k', 'l']
ES6 & without mutation: (October 2016)
const removeByIndex = (list, index) =>
[
...list.slice(0, index),
...list.slice(index + 1)
];
output = removeByIndex([33,22,11,44],1) //=> [33,11,44]
console.log(output)
Performance
Today (2019-12-09) I conduct performance tests on macOS v10.13.6 (High Sierra) for chosen solutions. I show delete (A), but I do not use it in comparison with other methods, because it left empty space in the array.
The conclusions
the fastest solution is array.splice (C) (except Safari for small arrays where it has the second time)
for big arrays, array.slice+splice (H) is the fastest immutable solution for Firefox and Safari; Array.from (B) is fastest in Chrome
mutable solutions are usually 1.5x-6x faster than immutable
for small tables on Safari, surprisingly the mutable solution (C) is slower than the immutable solution (G)
Details
In tests, I remove the middle element from the array in different ways. The A, C solutions are in-place. The B, D, E, F, G, H solutions are immutable.
Results for an array with 10 elements
In Chrome the array.splice (C) is the fastest in-place solution. The array.filter (D) is the fastest immutable solution. The slowest is array.slice (F). You can perform the test on your machine here.
Results for an array with 1.000.000 elements
In Chrome the array.splice (C) is the fastest in-place solution (the delete (C) is similar fast - but it left an empty slot in the array (so it does not perform a 'full remove')). The array.slice-splice (H) is the fastest immutable solution. The slowest is array.filter (D and E). You can perform the test on your machine here.
var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var log = (letter,array) => console.log(letter, array.join `,`);
function A(array) {
var index = array.indexOf(5);
delete array[index];
log('A', array);
}
function B(array) {
var index = array.indexOf(5);
var arr = Array.from(array);
arr.splice(index, 1)
log('B', arr);
}
function C(array) {
var index = array.indexOf(5);
array.splice(index, 1);
log('C', array);
}
function D(array) {
var arr = array.filter(item => item !== 5)
log('D', arr);
}
function E(array) {
var index = array.indexOf(5);
var arr = array.filter((item, i) => i !== index)
log('E', arr);
}
function F(array) {
var index = array.indexOf(5);
var arr = array.slice(0, index).concat(array.slice(index + 1))
log('F', arr);
}
function G(array) {
var index = array.indexOf(5);
var arr = [...array.slice(0, index), ...array.slice(index + 1)]
log('G', arr);
}
function H(array) {
var index = array.indexOf(5);
var arr = array.slice(0);
arr.splice(index, 1);
log('H', arr);
}
A([...a]);
B([...a]);
C([...a]);
D([...a]);
E([...a]);
F([...a]);
G([...a]);
H([...a]);
This snippet only presents code used in performance tests - it does not perform tests itself.
Comparison for browsers: Chrome v78.0.0, Safari v13.0.4, and Firefox v71.0.0
OK, for example you have the array below:
var num = [1, 2, 3, 4, 5];
And we want to delete number 4. You can simply use the below code:
num.splice(num.indexOf(4), 1); // num will be [1, 2, 3, 5];
If you are reusing this function, you write a reusable function which will be attached to the native array function like below:
Array.prototype.remove = Array.prototype.remove || function(x) {
const i = this.indexOf(x);
if(i===-1)
return;
this.splice(i, 1); // num.remove(5) === [1, 2, 3];
}
But how about if you have the below array instead with a few [5]s in the array?
var num = [5, 6, 5, 4, 5, 1, 5];
We need a loop to check them all, but an easier and more efficient way is using built-in JavaScript functions, so we write a function which use a filter like below instead:
const _removeValue = (arr, x) => arr.filter(n => n!==x);
//_removeValue([1, 2, 3, 4, 5, 5, 6, 5], 5) // Return [1, 2, 3, 4, 6]
Also there are third-party libraries which do help you to do this, like Lodash or Underscore. For more information, look at lodash _.pull, _.pullAt or _.without.
I'm pretty new to JavaScript and needed this functionality. I merely wrote this:
function removeFromArray(array, item, index) {
while((index = array.indexOf(item)) > -1) {
array.splice(index, 1);
}
}
Then when I want to use it:
//Set-up some dummy data
var dummyObj = {name:"meow"};
var dummyArray = [dummyObj, "item1", "item1", "item2"];
//Remove the dummy data
removeFromArray(dummyArray, dummyObj);
removeFromArray(dummyArray, "item2");
Output - As expected.
["item1", "item1"]
You may have different needs than I, so you can easily modify it to suit them. I hope this helps someone.
I want to answer based on ECMAScript 6. Assume you have an array like below:
let arr = [1,2,3,4];
If you want to delete at a special index like 2, write the below code:
arr.splice(2, 1); //=> arr became [1,2,4]
But if you want to delete a special item like 3 and you don't know its index, do like below:
arr = arr.filter(e => e !== 3); //=> arr became [1,2,4]
Hint: please use an arrow function for filter callback unless you will get an empty array.
If you have complex objects in the array you can use filters?
In situations where $.inArray or array.splice is not as easy to use. Especially if the objects are perhaps shallow in the array.
E.g. if you have an object with an Id field and you want the object removed from an array:
this.array = this.array.filter(function(element, i) {
return element.id !== idToRemove;
});
Update: This method is recommended only if you cannot use ECMAScript 2015 (formerly known as ES6). If you can use it, other answers here provide much neater implementations.
This gist here will solve your problem, and also deletes all occurrences of the argument instead of just 1 (or a specified value).
Array.prototype.destroy = function(obj){
// Return null if no objects were found and removed
var destroyed = null;
for(var i = 0; i < this.length; i++){
// Use while-loop to find adjacent equal objects
while(this[i] === obj){
// Remove this[i] and store it within destroyed
destroyed = this.splice(i, 1)[0];
}
}
return destroyed;
}
Usage:
var x = [1, 2, 3, 3, true, false, undefined, false];
x.destroy(3); // => 3
x.destroy(false); // => false
x; // => [1, 2, true, undefined]
x.destroy(true); // => true
x.destroy(undefined); // => undefined
x; // => [1, 2]
x.destroy(3); // => null
x; // => [1, 2]
You should never mutate your array as this is against the functional programming pattern. You can create a new array without referencing the one you want to change data of using the ECMAScript 6 method filter;
var myArray = [1, 2, 3, 4, 5, 6];
Suppose you want to remove 5 from the array, you can simply do it like this:
myArray = myArray.filter(value => value !== 5);
This will give you a new array without the value you wanted to remove. So the result will be:
[1, 2, 3, 4, 6]; // 5 has been removed from this array
For further understanding you can read the MDN documentation on Array.filter.
A more modern, ECMAScript 2015 (formerly known as Harmony or ES 6) approach. Given:
const items = [1, 2, 3, 4];
const index = 2;
Then:
items.filter((x, i) => i !== index);
Yielding:
[1, 2, 4]
You can use Babel and a polyfill service to ensure this is well supported across browsers.
You can do a backward loop to make sure not to screw up the indexes, if there are multiple instances of the element.
var myElement = "chocolate";
var myArray = ['chocolate', 'poptart', 'poptart', 'poptart', 'chocolate', 'poptart', 'poptart', 'chocolate'];
/* Important code */
for (var i = myArray.length - 1; i >= 0; i--) {
if (myArray[i] == myElement) myArray.splice(i, 1);
}
console.log(myArray);

Javascript equivalent of Python's zip function

Is there a javascript equivalent of Python's zip function? That is, given multiple arrays of equal lengths create an array of pairs.
For instance, if I have three arrays that look like this:
var array1 = [1, 2, 3];
var array2 = ['a','b','c'];
var array3 = [4, 5, 6];
The output array should be:
var outputArray = [[1,'a',4], [2,'b',5], [3,'c',6]]
2016 update:
Here's a snazzier Ecmascript 6 version:
zip= rows=>rows[0].map((_,c)=>rows.map(row=>row[c]))
Illustration equiv. to Python{zip(*args)}:
> zip([['row0col0', 'row0col1', 'row0col2'],
['row1col0', 'row1col1', 'row1col2']]);
[["row0col0","row1col0"],
["row0col1","row1col1"],
["row0col2","row1col2"]]
(and FizzyTea points out that ES6 has variadic argument syntax, so the following function definition will act like python, but see below for disclaimer... this will not be its own inverse so zip(zip(x)) will not equal x; though as Matt Kramer points out zip(...zip(...x))==x (like in regular python zip(*zip(*x))==x))
Alternative definition equiv. to Python{zip}:
> zip = (...rows) => [...rows[0]].map((_,c) => rows.map(row => row[c]))
> zip( ['row0col0', 'row0col1', 'row0col2'] ,
['row1col0', 'row1col1', 'row1col2'] );
// note zip(row0,row1), not zip(matrix)
same answer as above
(Do note that the ... syntax may have performance issues at this time, and possibly in the future, so if you use the second answer with variadic arguments, you may want to perf test it. That said it's been quite a while since it's been in the standard.)
Make sure to note the addendum if you wish to use this on strings (perhaps there's a better way to do it now with es6 iterables).
Here's a oneliner:
function zip(arrays) {
return arrays[0].map(function(_,i){
return arrays.map(function(array){return array[i]})
});
}
// > zip([[1,2],[11,22],[111,222]])
// [[1,11,111],[2,22,222]]]
// If you believe the following is a valid return value:
// > zip([])
// []
// then you can special-case it, or just do
// return arrays.length==0 ? [] : arrays[0].map(...)
The above assumes that the arrays are of equal size, as they should be. It also assumes you pass in a single list of lists argument, unlike Python's version where the argument list is variadic. If you want all of these "features", see below. It takes just about 2 extra lines of code.
The following will mimic Python's zip behavior on edge cases where the arrays are not of equal size, silently pretending the longer parts of arrays don't exist:
function zip() {
var args = [].slice.call(arguments);
var shortest = args.length==0 ? [] : args.reduce(function(a,b){
return a.length<b.length ? a : b
});
return shortest.map(function(_,i){
return args.map(function(array){return array[i]})
});
}
// > zip([1,2],[11,22],[111,222,333])
// [[1,11,111],[2,22,222]]]
// > zip()
// []
This will mimic Python's itertools.zip_longest behavior, inserting undefined where arrays are not defined:
function zip() {
var args = [].slice.call(arguments);
var longest = args.reduce(function(a,b){
return a.length>b.length ? a : b
}, []);
return longest.map(function(_,i){
return args.map(function(array){return array[i]})
});
}
// > zip([1,2],[11,22],[111,222,333])
// [[1,11,111],[2,22,222],[null,null,333]]
// > zip()
// []
If you use these last two version (variadic aka. multiple-argument versions), then zip is no longer its own inverse. To mimic the zip(*[...]) idiom from Python, you will need to do zip.apply(this, [...]) when you want to invert the zip function or if you want to similarly have a variable number of lists as input.
addendum:
To make this handle any iterable (e.g. in Python you can use zip on strings, ranges, map objects, etc.), you could define the following:
function iterView(iterable) {
// returns an array equivalent to the iterable
}
However if you write zip in the following way, even that won't be necessary:
function zip(arrays) {
return Array.apply(null,Array(arrays[0].length)).map(function(_,i){
return arrays.map(function(array){return array[i]})
});
}
Demo:
> JSON.stringify( zip(['abcde',[1,2,3,4,5]]) )
[["a",1],["b",2],["c",3],["d",4],["e",5]]
(Or you could use a range(...) Python-style function if you've written one already. Eventually you will be able to use ECMAScript array comprehensions or generators.)
Check out the library Underscore.
Underscore provides over 100 functions that support both your favorite workaday functional helpers: map, filter, invoke — as well as more specialized goodies: function binding, javascript templating, creating quick indexes, deep equality testing, and so on.
– Say the people who made it
I recently started using it specifically for the zip() function and it has left a great first impression. I am using jQuery and CoffeeScript, and it just goes perfectly with them. Underscore picks up right where they leave off and so far it hasn't let me down. Oh by the way, it's only 3kb minified.
Check it out:
_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
// returns [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]
Modern ES6 example with a generator:
function *zip (...iterables){
let iterators = iterables.map(i => i[Symbol.iterator]() )
while (true) {
let results = iterators.map(iter => iter.next() )
if (results.some(res => res.done) ) return
else yield results.map(res => res.value )
}
}
First, we get a list of iterables as iterators. This usually happens transparently, but here we do it explicitly, as we yield step-by-step until one of them is exhausted. We check if any of results (using the .some() method) in the given array is exhausted, and if so, we break the while loop.
In addition to ninjagecko's excellent and comprehensive answer, all it takes to zip two JS-arrays into a "tuple-mimic" is:
//Arrays: aIn, aOut
Array.prototype.map.call( aIn, function(e,i){return [e, aOut[i]];})
Explanation:
Since Javascript doesn't have a tuples type, functions for tuples, lists and sets wasn't a high priority in the language specification.
Otherwise, similar behavior is accessible in a straightforward manner via Array map in JS >1.6. (map is actually often implemented by JS engine makers in many >JS 1.4 engines, despite not specified).
The major difference to Python's zip, izip,... results from map's functional style, since map requires a function-argument. Additionally it is a function of the Array-instance. One may use Array.prototype.map instead, if an extra declaration for the input is an issue.
Example:
_tarrin = [0..constructor, function(){}, false, undefined, '', 100, 123.324,
2343243243242343242354365476453654625345345, 'sdf23423dsfsdf',
'sdf2324.234dfs','234,234fsf','100,100','100.100']
_parseInt = function(i){return parseInt(i);}
_tarrout = _tarrin.map(_parseInt)
_tarrin.map(function(e,i,a){return [e, _tarrout[i]]})
Result:
//'('+_tarrin.map(function(e,i,a){return [e, _tarrout[i]]}).join('),\n(')+')'
>>
(function Number() { [native code] },NaN),
(function (){},NaN),
(false,NaN),
(,NaN),
(,NaN),
(100,100),
(123.324,123),
(2.3432432432423434e+42,2),
(sdf23423dsfsdf,NaN),
(sdf2324.234dfs,NaN),
(234,234fsf,234),
(100,100,100),
(100.100,100)
Related Performance:
Using map over for-loops:
See: What is the most efficient way of merging [1,2] and [7,8] into [[1,7], [2,8]]
Note: the base types such as false and undefined do not posess a prototypal object-hierarchy and thus do not expose a toString function. Hence these are shown as empty in the output.
As parseInt's second argument is the base/number radix, to which to convert the number to, and since map passes the index as the second argument to its argument-function, a wrapper function is used.
Along other Python-like functions, pythonic offers a zip function, with the extra benefit of returning a lazy evaluated Iterator, similar to the behaviour of its Python counterpart:
import {zip, zipLongest} from 'pythonic';
const arr1 = ['a', 'b'];
const arr2 = ['c', 'd', 'e'];
for (const [first, second] of zip(arr1, arr2))
console.log(`first: ${first}, second: ${second}`);
// first: a, second: c
// first: b, second: d
for (const [first, second] of zipLongest(arr1, arr2))
console.log(`first: ${first}, second: ${second}`);
// first: a, second: c
// first: b, second: d
// first: undefined, second: e
// unzip
const [arrayFirst, arraySecond] = [...zip(...zip(arr1, arr2))];
Disclosure I'm author and maintainer of Pythonic
Python has two function to zip sequences: zip and itertools.zip_longest. An implementation in Javascript for the same functionality is this:
Implementation of Python`s zip on JS/ES6
const zip = (...arrays) => {
const length = Math.min(...arrays.map(arr => arr.length));
return Array.from({ length }, (value, index) => arrays.map((array => array[index])));
};
Results in:
console.log(zip(
[1, 2, 3, 'a'],
[667, false, -378, '337'],
[111],
[11, 221]
));
[ [ 1, 667, 111, 11 ] ]
console.log(zip(
[1, 2, 3, 'a'],
[667, false, -378, '337'],
[111, 212, 323, 433, '1111']
));
[ [ 1, 667, 111 ], [ 2, false, 212 ], [ 3, -378, 323 ], [ 'a',
'337', 433 ] ]
console.log(zip(
[1, 2, 3, 'a'],
[667, false, -378, '337'],
[111],
[]
));
[]
Implementation of Python`s zip_longest on JS/ES6
(https://docs.python.org/3.5/library/itertools.html?highlight=zip_longest#itertools.zip_longest)
const zipLongest = (placeholder = undefined, ...arrays) => {
const length = Math.max(...arrays.map(arr => arr.length));
return Array.from(
{ length }, (value, index) => arrays.map(
array => array.length - 1 >= index ? array[index] : placeholder
)
);
};
Results:
console.log(zipLongest(
undefined,
[1, 2, 3, 'a'],
[667, false, -378, '337'],
[111],
[]
));
[ [ 1, 667, 111, undefined ], [ 2, false, undefined, undefined ],
[ 3, -378, undefined, undefined ], [ 'a', '337', undefined,
undefined ] ]
console.log(zipLongest(
null,
[1, 2, 3, 'a'],
[667, false, -378, '337'],
[111],
[]
));
[ [ 1, 667, 111, null ], [ 2, false, null, null ], [ 3, -378,
null, null ], [ 'a', '337', null, null ] ]
console.log(zipLongest(
'Is None',
[1, 2, 3, 'a'],
[667, false, -378, '337'],
[111],
[]
));
[ [ 1, 667, 111, 'Is None' ], [ 2, false, 'Is None', 'Is None' ],
[ 3, -378, 'Is None', 'Is None' ], [ 'a', '337', 'Is None', 'Is
None' ] ]
You can make utility function by using ES6.
console.json = obj => console.log(JSON.stringify(obj));
const zip = (arr, ...arrs) =>
arr.map((val, i) => arrs.reduce((a, arr) => [...a, arr[i]], [val]));
// Example
const array1 = [1, 2, 3];
const array2 = ['a','b','c'];
const array3 = [4, 5, 6];
console.json(zip(array1, array2)); // [[1,"a"],[2,"b"],[3,"c"]]
console.json(zip(array1, array2, array3)); // [[1,"a",4],[2,"b",5],[3,"c",6]]
However, in above solution length of the first array defines the length of the output array.
Here is the solution in which you have more control over it. It's bit complex but worth it.
function _zip(func, args) {
const iterators = args.map(arr => arr[Symbol.iterator]());
let iterateInstances = iterators.map((i) => i.next());
ret = []
while(iterateInstances[func](it => !it.done)) {
ret.push(iterateInstances.map(it => it.value));
iterateInstances = iterators.map((i) => i.next());
}
return ret;
}
const array1 = [1, 2, 3];
const array2 = ['a','b','c'];
const array3 = [4, 5, 6];
const zipShort = (...args) => _zip('every', args);
const zipLong = (...args) => _zip('some', args);
console.log(zipShort(array1, array2, array3)) // [[1, 'a', 4], [2, 'b', 5], [3, 'c', 6]]
console.log(zipLong([1,2,3], [4,5,6, 7]))
// [
// [ 1, 4 ],
// [ 2, 5 ],
// [ 3, 6 ],
// [ undefined, 7 ]]
1. Npm Module: zip-array
I found an npm module that can be used as a javascript version of python zip:
zip-array - A javascript equivalent of Python's zip function. Merges together the values of each of the arrays.
https://www.npmjs.com/package/zip-array
2. tf.data.zip() in Tensorflow.js
Another alternate choice is for Tensorflow.js users: if you need a zip function in python to work with tensorflow datasets in Javascript, you can use tf.data.zip() in Tensorflow.js.
tf.data.zip() in Tensorflow.js documented at here
Original answer (see update below)
I modified flm's nifty answer to take an arbitrary number of arrays:
function* zip(arrays, i = 0) {
while (i<Math.min(...arrays.map(({length})=>length))) {
yield arrays.map((arr, j) => arr[j < arrays.length - 1 ? i : i++])
}
}
Updated answer
As pointed out by Tom Pohl this function can't deal with arrays with falsy values in. Here is an updated/improved version that can deal with any types and also unequal length arrays:
function* zip(arrays, i = 0) {
while (i<Math.min(...arrays.map(arr=>arr.length))) {
yield arrays.map((arr, j) => arr[j < arrays.length - 1 ? i : i++])
}
}
const arr1 = [false,0,1,2]
const arr2 = [100,null,99,98,97]
const arr3 = [7,8,undefined,"monkey","banana"]
console.log(...zip([arr1,arr2,arr3]))
Not built-in to Javascript itself. Some of the common Javascript frameworks (such as Prototype) provide an implementation, or you can write your own.
Like #Brandon, I recommend Underscore's zip function. However, it acts like zip_longest, appending undefined values as needed to return something the length of the longest input.
I used the mixin method to extend underscore with a zipShortest, which acts like Python's zip, based off of the library's own source for zip.
You can add the following to your common JS code and then call it as if it were part of underscore: _.zipShortest([1,2,3], ['a']) returns [[1, 'a']], for example.
// Underscore library addition - zip like python does, dominated by the shortest list
// The default injects undefineds to match the length of the longest list.
_.mixin({
zipShortest : function() {
var args = Array.Prototype.slice.call(arguments);
var length = _.min(_.pluck(args, 'length')); // changed max to min
var results = new Array(length);
for (var i = 0; i < length; i++) {
results[i] = _.pluck(args, "" + i);
}
return results;
}});
A variation of the lazy generator solution:
function* iter(it) {
yield* it;
}
function* zip(...its) {
its = its.map(iter);
while (true) {
let rs = its.map(it => it.next());
if (rs.some(r => r.done))
return;
yield rs.map(r => r.value);
}
}
for (let r of zip([1,2,3], [4,5,6,7], [8,9,0,11,22]))
console.log(r.join())
// the only change for "longest" is some -> every
function* zipLongest(...its) {
its = its.map(iter);
while (true) {
let rs = its.map(it => it.next());
if (rs.every(r => r.done))
return;
yield rs.map(r => r.value);
}
}
for (let r of zipLongest([1,2,3], [4,5,6,7], [8,9,0,11,22]))
console.log(r.join())
And this is the python's classic "n-group" idiom zip(*[iter(a)]*n):
triples = [...zip(...Array(3).fill(iter(a)))]
ES2020 shortest variant:
function * zip(arr1, arr2, i = 0) {
while(arr1[i] || arr2[i]) yield [arr1[i], arr2[i++]].filter(x => !!x);
}
[ ...zip(arr1, arr2) ] // result
You could reduce the array of arrays and map new array by taking the result of the index of the inner array.
var array1 = [1, 2, 3],
array2 = ['a','b','c'],
array3 = [4, 5, 6],
array = [array1, array2, array3],
transposed = array.reduce((r, a) => a.map((v, i) => (r[i] || []).concat(v)), []);
console.log(transposed);
Fun with spread.
const
transpose = (r, a) => a.map((v, i) => [...(r[i] || []), v]),
array1 = [1, 2, 3],
array2 = ['a','b','c'],
array3 = [4, 5, 6],
transposed = [array1, array2, array3].reduce(transpose, []);
console.log(transposed);
I took a run at this in pure JS wondering how the plugins posted above got the job done. Here's my result. I'll preface this by saying that I have no idea how stable this will be in IE and the like. It's just a quick mockup.
init();
function init() {
var one = [0, 1, 2, 3];
var two = [4, 5, 6, 7];
var three = [8, 9, 10, 11, 12];
var four = zip(one, two, one);
//returns array
//four = zip(one, two, three);
//returns false since three.length !== two.length
console.log(four);
}
function zip() {
for (var i = 0; i < arguments.length; i++) {
if (!arguments[i].length || !arguments.toString()) {
return false;
}
if (i >= 1) {
if (arguments[i].length !== arguments[i - 1].length) {
return false;
}
}
}
var zipped = [];
for (var j = 0; j < arguments[0].length; j++) {
var toBeZipped = [];
for (var k = 0; k < arguments.length; k++) {
toBeZipped.push(arguments[k][j]);
}
zipped.push(toBeZipped);
}
return zipped;
}
It's not bulletproof, but it's still interesting.
A generator approach to pythons zip function.
function* zip(...arrs){
for(let i = 0; i < arrs[0].length; i++){
a = arrs.map(e=>e[i])
if(a.indexOf(undefined) == -1 ){yield a }else{return undefined;}
}
}
// use as multiple iterators
for( let [a,b,c] of zip([1, 2, 3, 4], ['a', 'b', 'c', 'd'], ['hi', 'hello', 'howdy', 'how are you']) )
console.log(a,b,c)
// creating new array with the combined arrays
let outputArr = []
for( let arr of zip([1, 2, 3, 4], ['a', 'b', 'c', 'd'], ['hi', 'hello', 'howdy', 'how are you']) )
outputArr.push(arr)
I have created a simple function to do so with a option to provide an zipper function
function zip(zipper, ...arrays) {
if (zipper instanceof Array) {
arrays.unshift(zipper)
zipper = (...elements) => elements
}
const length = Math.min(...arrays.map(array => array.length))
const zipped = []
for (let i = 0; i < length; i++) {
zipped.push(zipper(...arrays.map(array => array[i])))
}
return zipped
}
https://gist.github.com/AmrIKhudair/4b740149c29c492859e00f451832975b
I'm not a javascript guy but I feel like many of these answers are trying to find the cutest and most clever solution using Array.map which is fine, but for someone like me that doesn't use javascript every day here are some alternatives that might possibly be a bit more readable.
Maybe a way to avoid some cute and clever code would be:
function zip(a,b){
// pre-allocate an array to hold the results
rval=Array(Math.max(a.length, b.length));
for(i=0; i<rval.length; i++){
rval[i]=[a[i],b[i]]
}
return rval
}
If you like generators:
function* _zip(a,b){
len = Math.max(a.length, b.length) // handle different sized arrays
for(i=0; i<len; i++) { yield [a[i],b[i]] }
}
Or if you really want to use Array.map:
function map(a,b){
x = a.length > b.length ? a : b // call map on the biggest array
return x.map((_,i)=>[a[i],b[i]])
}
As I said, I'm not an everyday javascript guy so, these aren't going to be the most elegant solutions but they are readable to me.
Below is a fast and efficient way of doing this, using iter-ops library, operator zip:
const {pipe, zip} = require('iter-ops');
const i = pipe(array1, zip(array2, array3));
console.log(...i); //=> [ 1, 'a', 4 ] [ 2, 'b', 5 ] [ 3, 'c', 6 ]
The library processes all inputs as iterables, so they are iterated over just once. And it can handle, in the same way, all types of iterable objects - Iterable, AsyncIterable, Iterator, AsyncIterator.
P.S. I'm the author of iter-ops.
The Mochikit library provides this and many other Python-like functions. developer of Mochikit is also a Python fan, so it has the general style of Python, and also the wraps the async calls in a twisted-like framework.
There is no equivalent function. If you have only a few arrays you should use a for loop to get an index and then use the index to access the arrays:
var array1 = [1, 2, 3];
var array2 = ['a','b','c'];
for (let i = 0; i < Math.min(array1.length, array2.length); i++) {
doStuff(array1[i], array2[i]);
}
You can have an inner loop over the arrays if you have more.
Here is my solution
let zip = (a, b) => (a.length < b.length
? a.map((e, i) => [e, b[i]])
: b.map((e, i) => [a[i], e]))
This shaves a line off Ddi's iterator-based answer:
function* zip(...toZip) {
const iterators = toZip.map((arg) => arg[Symbol.iterator]());
const next = () => toZip = iterators.map((iter) => iter.next());
while (next().every((item) => !item.done)) {
yield toZip.map((item) => item.value);
}
}
If you are fine with ES6:
const zip = (arr,...arrs) =>(
arr.map(
(v,i) => arrs.reduce((a,arr)=>[...a, arr[i]], [v])))

Categories