How to add items to an object inside a javascript array? [duplicate] - javascript

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
How do I append an object (such as a string or number) to an array in JavaScript?

Use the Array.prototype.push method to append values to the end of an array:
// initialize array
var arr = [
"Hi",
"Hello",
"Bonjour"
];
// append new value to the array
arr.push("Hola");
console.log(arr);
You can use the push() function to append more than one value to an array in a single call:
// initialize array
var arr = ["Hi", "Hello", "Bonjour", "Hola"];
// append multiple values to the array
arr.push("Salut", "Hey");
// display all values
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Update
If you want to add the items of one array to another array, you can use firstArray.concat(secondArray):
var arr = [
"apple",
"banana",
"cherry"
];
// Do not forget to assign the result as, unlike push, concat does not change the existing array
arr = arr.concat([
"dragonfruit",
"elderberry",
"fig"
]);
console.log(arr);
Update
Just an addition to this answer if you want to prepend any value to the start of an array (i.e. first index) then you can use Array.prototype.unshift for this purpose.
var arr = [1, 2, 3];
arr.unshift(0);
console.log(arr);
It also supports appending multiple values at once just like push.
Update
Another way with ES6 syntax is to return a new array with the spread syntax. This leaves the original array unchanged, but returns a new array with new items appended, compliant with the spirit of functional programming.
const arr = [
"Hi",
"Hello",
"Bonjour",
];
const newArr = [
...arr,
"Salut",
];
console.log(newArr);

If you're only appending a single variable, then push() works just fine. If you need to append another array, use concat():
var ar1 = [1, 2, 3];
var ar2 = [4, 5, 6];
var ar3 = ar1.concat(ar2);
alert(ar1);
alert(ar2);
alert(ar3);
The concat does not affect ar1 and ar2 unless reassigned, for example:
var ar1 = [1, 2, 3];
var ar2 = [4, 5, 6];
ar1 = ar1.concat(ar2);
alert(ar1);
There is a lot of great information on JavaScript Reference.

Some quick benchmarking (each test = 500k appended elements and the results are averages of multiple runs) showed the following:
Firefox 3.6 (Mac):
Small arrays: arr[arr.length] = b is faster (300ms vs. 800ms)
Large arrays: arr.push(b) is faster (500ms vs. 900ms)
Safari 5.0 (Mac):
Small arrays: arr[arr.length] = b is faster (90ms vs. 115ms)
Large arrays: arr[arr.length] = b is faster (160ms vs. 185ms)
Google Chrome 6.0 (Mac):
Small arrays: No significant difference (and Chrome is FAST! Only ~38ms !!)
Large arrays: No significant difference (160ms)
I like the arr.push() syntax better, but I think I'd be better off with the arr[arr.length] Version, at least in raw speed. I'd love to see the results of an IE run though.
My benchmarking loops:
function arrpush_small() {
var arr1 = [];
for (a = 0; a < 100; a++)
{
arr1 = [];
for (i = 0; i < 5000; i++)
{
arr1.push('elem' + i);
}
}
}
function arrlen_small() {
var arr2 = [];
for (b = 0; b < 100; b++)
{
arr2 = [];
for (j = 0; j < 5000; j++)
{
arr2[arr2.length] = 'elem' + j;
}
}
}
function arrpush_large() {
var arr1 = [];
for (i = 0; i < 500000; i++)
{
arr1.push('elem' + i);
}
}
function arrlen_large() {
var arr2 = [];
for (j = 0; j < 500000; j++)
{
arr2[arr2.length] = 'elem' + j;
}
}

I think it's worth mentioning that push can be called with multiple arguments, which will be appended to the array in order. For example:
var arr = ['first'];
arr.push('second', 'third');
console.log(arr);
As a result of this you can use push.apply to append an array to another array like so:
var arr = ['first'];
arr.push('second', 'third');
arr.push.apply(arr, ['forth', 'fifth']);
console.log(arr);
Annotated ES5 has more info on exactly what push and apply do.
2016 update: with spread, you don't need that apply anymore, like:
var arr = ['first'];
arr.push('second', 'third');
arr.push(...['fourth', 'fifth']);
console.log(arr) ;

You can use the push and apply functions to append two arrays.
var array1 = [11, 32, 75];
var array2 = [99, 67, 34];
Array.prototype.push.apply(array1, array2);
console.log(array1);
It will append array2 to array1. Now array1 contains [11, 32, 75, 99, 67, 34].
This code is much simpler than writing for loops to copy each and every items in the array.

With the new ES6 spread operator, joining two arrays using push becomes even easier:
var arr = [1, 2, 3, 4, 5];
var arr2 = [6, 7, 8, 9, 10];
arr.push(...arr2);
console.log(arr);
This adds the contents of arr2 onto the end of arr.
Babel REPL Example

If arr is an array, and val is the value you wish to add use:
arr.push(val);
E.g.
var arr = ['a', 'b', 'c'];
arr.push('d');
console.log(arr);

Use concat:
a = [1, 2, 3];
b = [3, 4, 5];
a = a.concat(b);
console.log(a);

JavaScript with the ECMAScript 5 (ES5) standard which is supported by most browsers now, you can use apply() to append array1 to array2.
var array1 = [3, 4, 5];
var array2 = [1, 2];
Array.prototype.push.apply(array2, array1);
console.log(array2); // [1, 2, 3, 4, 5]
JavaScript with ECMAScript 6 (ES6) standard which is supported by Chrome, Firefox, Internet Explorer, and Edge, you can use the spread operator:
"use strict";
let array1 = [3, 4, 5];
let array2 = [1, 2];
array2.push(...array1);
console.log(array2); // [1, 2, 3, 4, 5]
The spread operator will replace array2.push(...array1); with array2.push(3, 4, 5); when the browser is thinking the logic.
Bonus point
If you'd like to create another variable to store all the items from both arrays, you can do this:
ES5 var combinedArray = array1.concat(array2);
ES6 const combinedArray = [...array1, ...array2]
The spread operator (...) is to spread out all items from a collection.

If you want to append two arrays -
var a = ['a', 'b'];
var b = ['c', 'd'];
then you could use:
var c = a.concat(b);
And if you want to add record g to array (var a=[]) then you could use:
a.push('g');

There are a couple of ways to append an array in JavaScript:
1) The push() method adds one or more elements to the end of an array and returns the new length of the array.
var a = [1, 2, 3];
a.push(4, 5);
console.log(a);
Output:
[1, 2, 3, 4, 5]
2) The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array:
var a = [1, 2, 3];
a.unshift(4, 5);
console.log(a);
Output:
[4, 5, 1, 2, 3]
3) The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
var arr1 = ["a", "b", "c"];
var arr2 = ["d", "e", "f"];
var arr3 = arr1.concat(arr2);
console.log(arr3);
Output:
[ "a", "b", "c", "d", "e", "f" ]
4) You can use the array's .length property to add an element to the end of the array:
var ar = ['one', 'two', 'three'];
ar[ar.length] = 'four';
console.log( ar );
Output:
["one", "two", "three", "four"]
5) The splice() method changes the content of an array by removing existing elements and/or adding new elements:
var myFish = ["angel", "clown", "mandarin", "surgeon"];
myFish.splice(4, 0, "nemo");
//array.splice(start, deleteCount, item1, item2, ...)
console.log(myFish);
Output:
["angel", "clown", "mandarin", "surgeon","nemo"]
6) You can also add a new element to an array simply by specifying a new index and assigning a value:
var ar = ['one', 'two', 'three'];
ar[3] = 'four'; // add new element to ar
console.log(ar);
Output:
["one", "two","three","four"]

The push() method adds new items to the end of an array, and returns the new length. Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
// The result of fruits will be:
Banana, Orange, Apple, Mango, Kiwi
The exact answer to your question is already answered, but let's look at some other ways to add items to an array.
The unshift() method adds new items to the beginning of an array, and returns the new length. Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon", "Pineapple");
// The result of fruits will be:
Lemon, Pineapple, Banana, Orange, Apple, Mango
And lastly, the concat() method is used to join two or more arrays. Example:
var fruits = ["Banana", "Orange"];
var moreFruits = ["Apple", "Mango", "Lemon"];
var allFruits = fruits.concat(moreFruits);
// The values of the children array will be:
Banana, Orange, Apple, Mango, Lemon

Now, you can take advantage of ES6 syntax and just do
let array = [1, 2];
console.log([...array, 3]);
keeping the original array immutable.

Append a single element
// Append to the end
arrName.push('newName1');
// Prepend to the start
arrName.unshift('newName1');
// Insert at index 1
arrName.splice(1, 0,'newName1');
// 1: index number, 0: number of element to remove, newName1: new element
// Replace index 3 (of exists), add new element otherwise.
arrName[3] = 'newName1';
Append multiple elements
// Insert from index number 1
arrName.splice(1, 0,'newElemenet1', 'newElemenet2', 'newElemenet3');
// 1: index number from where insert starts,
// 0: number of element to remove,
//newElemenet1,2,3: new elements
Append an array
// Join two or more arrays
arrName.concat(newAry1, newAry2);
//newAry1,newAry2: Two different arrays which are to be combined (concatenated) to an existing array

If you know the highest index (such as stored in a variable "i") then you can do
myArray[i + 1] = someValue;
However, if you don't know then you can either use
myArray.push(someValue);
as other answers suggested, or you can use
myArray[myArray.length] = someValue;
Note that the array is zero based so .length returns the highest index plus one.
Also note that you don't have to add in order and you can actually skip values, as in
myArray[myArray.length + 1000] = someValue;
In which case the values in between will have a value of undefined.
It is therefore a good practice when looping through a JavaScript to verify that a value actually exists at that point.
This can be done by something like the following:
if(myArray[i] === "undefined"){ continue; }
If you are certain that you don't have any zeros in the array then you can just do:
if(!myArray[i]){ continue; }
Of course, make sure in this case that you don't use as the condition myArray[i] (as some people over the Internet suggest based on the end that as soon as i is greater than the highest index, it will return undefined which evaluates to false).

You can do it using JavaScript Spread Operator Syntax:
// Initialize the array
var arr = [
"Hi",
"Hello",
"Bangladesh"
];
// Append a new value to the array
arr = [...arr, "Feni"];
// Or you can add a variable value
var testValue = "Cool";
arr = [...arr, testValue ];
console.log(arr);
// Final output [ 'Hi', 'Hello', 'Bangladesh', 'Feni', 'Cool' ]

If you are using ES6 you can use spread operator to do it.
var arr = [
"apple",
"banana",
"cherry"
];
var arr2 = [
"dragonfruit",
"elderberry",
"fig"
];
arr.push(...arr2);

concat(), of course, can be used with two-dimensional arrays as well. No looping required.
var a = [
[1, 2],
[3, 4] ];
var b = [
["a", "b"],
["c", "d"] ];
b = b.concat(a);
alert(b[2][1]); // Result: 2

Just want to add a snippet for non-destructive addition of an element.
var newArr = oldArr.concat([newEl]);

Let the array length property do the work:
myarray[myarray.length] = 'new element value added to the end of the array';
myarray.length returns the number of strings in the array.
JavaScript is zero-based, so the next element key of the array will be the current length of the array.
Example:
var myarray = [0, 1, 2, 3],
myarrayLength = myarray.length; // myarrayLength is set to 4

Append a value to an array
Since Array.prototype.push adds one or more elements to the end of an array and returns the new length of the array, sometimes we want just to get the new up-to-date array so we can do something like so:
const arr = [1, 2, 3];
const val = 4;
arr.concat([val]); // [1, 2, 3, 4]
Or just:
[...arr, val] // [1, 2, 3, 4]

Append a single item
To append a single item to an array, use the push() method provided by the Array object:
const fruits = ['banana', 'pear', 'apple']
fruits.push('mango')
console.log(fruits)
push() mutates the original array.
To create a new array instead, use the concat() Array method:
const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat('mango')
console.log(allfruits)
Notice that concat() does not actually add an item to the array, but creates a new array, which you can assign to another variable, or reassign to the original array (declaring it as let, as you cannot reassign a const):
const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat('mango')
console.log(allfruits)
let fruits = ['banana', 'pear', 'apple']
fruits = fruits.concat('mango')
Append multiple items
To append a multiple item to an array, you can use push() by calling it with multiple arguments:
const fruits = ['banana', 'pear', 'apple']
fruits.push('mango', 'melon', 'avocado')
console.log(fruits)
You can also use the concat() method you saw before, passing a list of items separated by a comma:
const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat('mango', 'melon', 'avocado')
console.log(allfruits)
or an array:
const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat(['mango', 'melon', 'avocado'])
console.log(allfruits)
Remember that as described previously this method does not mutate the original array, but it returns a new array.
Originally posted at

If you want to combine two arrays without the duplicate you may try the code below:
array_merge = function (arr1, arr2) {
return arr1.concat(arr2.filter(function(item){
return arr1.indexOf(item) < 0;
}))
}
Usage:
array1 = ['1', '2', '3']
array2 = ['2', '3', '4', '5']
combined_array = array_merge(array1, array2)
Output:
[1,2,3,4,5]

You .push() that value in.
Example: array.push(value);

If you want to append a single value into an array, simply use the push method. It will add a new element at the end of the array.
But if you intend to add multiple elements then store the elements in a new array and concat the second array with the first array...either way you wish.
arr=['a','b','c'];
arr.push('d');
//now print the array in console.log and it will contain 'a','b','c','d' as elements.
console.log(array);

We don't have an append function for Array in JavaScript, but we have push and unshift. Imagine you have the array below:
var arr = [1, 2, 3, 4, 5];
And we like to append a value to this array. We can do arr.push(6), and it will add 6 to the end of the array:
arr.push(6); // Returns [1, 2, 3, 4, 5, 6];
Also we can use unshift, look at how we can apply this:
arr.unshift(0); // Returns [0, 1, 2, 3, 4, 5];
They are main functions to add or append new values to the arrays.

You can use the push() if you want to add values,
e.g. arr.push("Test1", "Test2");.
If you have array you can use concat(), e.g. Array1.concat(Array2).
If you have just one element to add, you can also try the length method, e.g. array[aray.length] = 'test';.

Appending items on an array
let fruits = ["orange", "banana", "apple", "lemon"]; /* Array declaration */
fruits.push("avacado"); /* Adding an element to the array */
/* Displaying elements of the array */
for(var i=0; i < fruits.length; i++){
console.log(fruits[i]);
}

You can use the push method.
Array.prototype.append = function(destArray){
destArray = destArray || [];
this.push.call(this, ...destArray);
return this;
}
var arr = [1,2,5,67];
var arr1 = [7,4,7,8];
console.log(arr.append(arr1)); // [7, 4, 7, 8, 1, 4, 5, 67, 7]
console.log(arr.append("Hola")) // [1, 2, 5, 67, 7, 4, 7, 8, "H", "o", "l", "a"]

push() adds a new element to the end of an array.
pop() removes an element from the end of an array.
To append an object (such as a string or number) to an array, use:
array.push(toAppend);

Related

forEach number to a new array rather than a list [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
How do I append an object (such as a string or number) to an array in JavaScript?
Use the Array.prototype.push method to append values to the end of an array:
// initialize array
var arr = [
"Hi",
"Hello",
"Bonjour"
];
// append new value to the array
arr.push("Hola");
console.log(arr);
You can use the push() function to append more than one value to an array in a single call:
// initialize array
var arr = ["Hi", "Hello", "Bonjour", "Hola"];
// append multiple values to the array
arr.push("Salut", "Hey");
// display all values
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Update
If you want to add the items of one array to another array, you can use firstArray.concat(secondArray):
var arr = [
"apple",
"banana",
"cherry"
];
// Do not forget to assign the result as, unlike push, concat does not change the existing array
arr = arr.concat([
"dragonfruit",
"elderberry",
"fig"
]);
console.log(arr);
Update
Just an addition to this answer if you want to prepend any value to the start of an array (i.e. first index) then you can use Array.prototype.unshift for this purpose.
var arr = [1, 2, 3];
arr.unshift(0);
console.log(arr);
It also supports appending multiple values at once just like push.
Update
Another way with ES6 syntax is to return a new array with the spread syntax. This leaves the original array unchanged, but returns a new array with new items appended, compliant with the spirit of functional programming.
const arr = [
"Hi",
"Hello",
"Bonjour",
];
const newArr = [
...arr,
"Salut",
];
console.log(newArr);
If you're only appending a single variable, then push() works just fine. If you need to append another array, use concat():
var ar1 = [1, 2, 3];
var ar2 = [4, 5, 6];
var ar3 = ar1.concat(ar2);
alert(ar1);
alert(ar2);
alert(ar3);
The concat does not affect ar1 and ar2 unless reassigned, for example:
var ar1 = [1, 2, 3];
var ar2 = [4, 5, 6];
ar1 = ar1.concat(ar2);
alert(ar1);
There is a lot of great information on JavaScript Reference.
Some quick benchmarking (each test = 500k appended elements and the results are averages of multiple runs) showed the following:
Firefox 3.6 (Mac):
Small arrays: arr[arr.length] = b is faster (300ms vs. 800ms)
Large arrays: arr.push(b) is faster (500ms vs. 900ms)
Safari 5.0 (Mac):
Small arrays: arr[arr.length] = b is faster (90ms vs. 115ms)
Large arrays: arr[arr.length] = b is faster (160ms vs. 185ms)
Google Chrome 6.0 (Mac):
Small arrays: No significant difference (and Chrome is FAST! Only ~38ms !!)
Large arrays: No significant difference (160ms)
I like the arr.push() syntax better, but I think I'd be better off with the arr[arr.length] Version, at least in raw speed. I'd love to see the results of an IE run though.
My benchmarking loops:
function arrpush_small() {
var arr1 = [];
for (a = 0; a < 100; a++)
{
arr1 = [];
for (i = 0; i < 5000; i++)
{
arr1.push('elem' + i);
}
}
}
function arrlen_small() {
var arr2 = [];
for (b = 0; b < 100; b++)
{
arr2 = [];
for (j = 0; j < 5000; j++)
{
arr2[arr2.length] = 'elem' + j;
}
}
}
function arrpush_large() {
var arr1 = [];
for (i = 0; i < 500000; i++)
{
arr1.push('elem' + i);
}
}
function arrlen_large() {
var arr2 = [];
for (j = 0; j < 500000; j++)
{
arr2[arr2.length] = 'elem' + j;
}
}
I think it's worth mentioning that push can be called with multiple arguments, which will be appended to the array in order. For example:
var arr = ['first'];
arr.push('second', 'third');
console.log(arr);
As a result of this you can use push.apply to append an array to another array like so:
var arr = ['first'];
arr.push('second', 'third');
arr.push.apply(arr, ['forth', 'fifth']);
console.log(arr);
Annotated ES5 has more info on exactly what push and apply do.
2016 update: with spread, you don't need that apply anymore, like:
var arr = ['first'];
arr.push('second', 'third');
arr.push(...['fourth', 'fifth']);
console.log(arr) ;
You can use the push and apply functions to append two arrays.
var array1 = [11, 32, 75];
var array2 = [99, 67, 34];
Array.prototype.push.apply(array1, array2);
console.log(array1);
It will append array2 to array1. Now array1 contains [11, 32, 75, 99, 67, 34].
This code is much simpler than writing for loops to copy each and every items in the array.
With the new ES6 spread operator, joining two arrays using push becomes even easier:
var arr = [1, 2, 3, 4, 5];
var arr2 = [6, 7, 8, 9, 10];
arr.push(...arr2);
console.log(arr);
This adds the contents of arr2 onto the end of arr.
Babel REPL Example
If arr is an array, and val is the value you wish to add use:
arr.push(val);
E.g.
var arr = ['a', 'b', 'c'];
arr.push('d');
console.log(arr);
Use concat:
a = [1, 2, 3];
b = [3, 4, 5];
a = a.concat(b);
console.log(a);
JavaScript with the ECMAScript 5 (ES5) standard which is supported by most browsers now, you can use apply() to append array1 to array2.
var array1 = [3, 4, 5];
var array2 = [1, 2];
Array.prototype.push.apply(array2, array1);
console.log(array2); // [1, 2, 3, 4, 5]
JavaScript with ECMAScript 6 (ES6) standard which is supported by Chrome, Firefox, Internet Explorer, and Edge, you can use the spread operator:
"use strict";
let array1 = [3, 4, 5];
let array2 = [1, 2];
array2.push(...array1);
console.log(array2); // [1, 2, 3, 4, 5]
The spread operator will replace array2.push(...array1); with array2.push(3, 4, 5); when the browser is thinking the logic.
Bonus point
If you'd like to create another variable to store all the items from both arrays, you can do this:
ES5 var combinedArray = array1.concat(array2);
ES6 const combinedArray = [...array1, ...array2]
The spread operator (...) is to spread out all items from a collection.
If you want to append two arrays -
var a = ['a', 'b'];
var b = ['c', 'd'];
then you could use:
var c = a.concat(b);
And if you want to add record g to array (var a=[]) then you could use:
a.push('g');
There are a couple of ways to append an array in JavaScript:
1) The push() method adds one or more elements to the end of an array and returns the new length of the array.
var a = [1, 2, 3];
a.push(4, 5);
console.log(a);
Output:
[1, 2, 3, 4, 5]
2) The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array:
var a = [1, 2, 3];
a.unshift(4, 5);
console.log(a);
Output:
[4, 5, 1, 2, 3]
3) The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
var arr1 = ["a", "b", "c"];
var arr2 = ["d", "e", "f"];
var arr3 = arr1.concat(arr2);
console.log(arr3);
Output:
[ "a", "b", "c", "d", "e", "f" ]
4) You can use the array's .length property to add an element to the end of the array:
var ar = ['one', 'two', 'three'];
ar[ar.length] = 'four';
console.log( ar );
Output:
["one", "two", "three", "four"]
5) The splice() method changes the content of an array by removing existing elements and/or adding new elements:
var myFish = ["angel", "clown", "mandarin", "surgeon"];
myFish.splice(4, 0, "nemo");
//array.splice(start, deleteCount, item1, item2, ...)
console.log(myFish);
Output:
["angel", "clown", "mandarin", "surgeon","nemo"]
6) You can also add a new element to an array simply by specifying a new index and assigning a value:
var ar = ['one', 'two', 'three'];
ar[3] = 'four'; // add new element to ar
console.log(ar);
Output:
["one", "two","three","four"]
The push() method adds new items to the end of an array, and returns the new length. Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
// The result of fruits will be:
Banana, Orange, Apple, Mango, Kiwi
The exact answer to your question is already answered, but let's look at some other ways to add items to an array.
The unshift() method adds new items to the beginning of an array, and returns the new length. Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon", "Pineapple");
// The result of fruits will be:
Lemon, Pineapple, Banana, Orange, Apple, Mango
And lastly, the concat() method is used to join two or more arrays. Example:
var fruits = ["Banana", "Orange"];
var moreFruits = ["Apple", "Mango", "Lemon"];
var allFruits = fruits.concat(moreFruits);
// The values of the children array will be:
Banana, Orange, Apple, Mango, Lemon
Now, you can take advantage of ES6 syntax and just do
let array = [1, 2];
console.log([...array, 3]);
keeping the original array immutable.
Append a single element
// Append to the end
arrName.push('newName1');
// Prepend to the start
arrName.unshift('newName1');
// Insert at index 1
arrName.splice(1, 0,'newName1');
// 1: index number, 0: number of element to remove, newName1: new element
// Replace index 3 (of exists), add new element otherwise.
arrName[3] = 'newName1';
Append multiple elements
// Insert from index number 1
arrName.splice(1, 0,'newElemenet1', 'newElemenet2', 'newElemenet3');
// 1: index number from where insert starts,
// 0: number of element to remove,
//newElemenet1,2,3: new elements
Append an array
// Join two or more arrays
arrName.concat(newAry1, newAry2);
//newAry1,newAry2: Two different arrays which are to be combined (concatenated) to an existing array
If you know the highest index (such as stored in a variable "i") then you can do
myArray[i + 1] = someValue;
However, if you don't know then you can either use
myArray.push(someValue);
as other answers suggested, or you can use
myArray[myArray.length] = someValue;
Note that the array is zero based so .length returns the highest index plus one.
Also note that you don't have to add in order and you can actually skip values, as in
myArray[myArray.length + 1000] = someValue;
In which case the values in between will have a value of undefined.
It is therefore a good practice when looping through a JavaScript to verify that a value actually exists at that point.
This can be done by something like the following:
if(myArray[i] === "undefined"){ continue; }
If you are certain that you don't have any zeros in the array then you can just do:
if(!myArray[i]){ continue; }
Of course, make sure in this case that you don't use as the condition myArray[i] (as some people over the Internet suggest based on the end that as soon as i is greater than the highest index, it will return undefined which evaluates to false).
You can do it using JavaScript Spread Operator Syntax:
// Initialize the array
var arr = [
"Hi",
"Hello",
"Bangladesh"
];
// Append a new value to the array
arr = [...arr, "Feni"];
// Or you can add a variable value
var testValue = "Cool";
arr = [...arr, testValue ];
console.log(arr);
// Final output [ 'Hi', 'Hello', 'Bangladesh', 'Feni', 'Cool' ]
If you are using ES6 you can use spread operator to do it.
var arr = [
"apple",
"banana",
"cherry"
];
var arr2 = [
"dragonfruit",
"elderberry",
"fig"
];
arr.push(...arr2);
concat(), of course, can be used with two-dimensional arrays as well. No looping required.
var a = [
[1, 2],
[3, 4] ];
var b = [
["a", "b"],
["c", "d"] ];
b = b.concat(a);
alert(b[2][1]); // Result: 2
Just want to add a snippet for non-destructive addition of an element.
var newArr = oldArr.concat([newEl]);
Let the array length property do the work:
myarray[myarray.length] = 'new element value added to the end of the array';
myarray.length returns the number of strings in the array.
JavaScript is zero-based, so the next element key of the array will be the current length of the array.
Example:
var myarray = [0, 1, 2, 3],
myarrayLength = myarray.length; // myarrayLength is set to 4
Append a value to an array
Since Array.prototype.push adds one or more elements to the end of an array and returns the new length of the array, sometimes we want just to get the new up-to-date array so we can do something like so:
const arr = [1, 2, 3];
const val = 4;
arr.concat([val]); // [1, 2, 3, 4]
Or just:
[...arr, val] // [1, 2, 3, 4]
Append a single item
To append a single item to an array, use the push() method provided by the Array object:
const fruits = ['banana', 'pear', 'apple']
fruits.push('mango')
console.log(fruits)
push() mutates the original array.
To create a new array instead, use the concat() Array method:
const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat('mango')
console.log(allfruits)
Notice that concat() does not actually add an item to the array, but creates a new array, which you can assign to another variable, or reassign to the original array (declaring it as let, as you cannot reassign a const):
const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat('mango')
console.log(allfruits)
let fruits = ['banana', 'pear', 'apple']
fruits = fruits.concat('mango')
Append multiple items
To append a multiple item to an array, you can use push() by calling it with multiple arguments:
const fruits = ['banana', 'pear', 'apple']
fruits.push('mango', 'melon', 'avocado')
console.log(fruits)
You can also use the concat() method you saw before, passing a list of items separated by a comma:
const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat('mango', 'melon', 'avocado')
console.log(allfruits)
or an array:
const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat(['mango', 'melon', 'avocado'])
console.log(allfruits)
Remember that as described previously this method does not mutate the original array, but it returns a new array.
Originally posted at
If you want to combine two arrays without the duplicate you may try the code below:
array_merge = function (arr1, arr2) {
return arr1.concat(arr2.filter(function(item){
return arr1.indexOf(item) < 0;
}))
}
Usage:
array1 = ['1', '2', '3']
array2 = ['2', '3', '4', '5']
combined_array = array_merge(array1, array2)
Output:
[1,2,3,4,5]
You .push() that value in.
Example: array.push(value);
If you want to append a single value into an array, simply use the push method. It will add a new element at the end of the array.
But if you intend to add multiple elements then store the elements in a new array and concat the second array with the first array...either way you wish.
arr=['a','b','c'];
arr.push('d');
//now print the array in console.log and it will contain 'a','b','c','d' as elements.
console.log(array);
We don't have an append function for Array in JavaScript, but we have push and unshift. Imagine you have the array below:
var arr = [1, 2, 3, 4, 5];
And we like to append a value to this array. We can do arr.push(6), and it will add 6 to the end of the array:
arr.push(6); // Returns [1, 2, 3, 4, 5, 6];
Also we can use unshift, look at how we can apply this:
arr.unshift(0); // Returns [0, 1, 2, 3, 4, 5];
They are main functions to add or append new values to the arrays.
You can use the push() if you want to add values,
e.g. arr.push("Test1", "Test2");.
If you have array you can use concat(), e.g. Array1.concat(Array2).
If you have just one element to add, you can also try the length method, e.g. array[aray.length] = 'test';.
Appending items on an array
let fruits = ["orange", "banana", "apple", "lemon"]; /* Array declaration */
fruits.push("avacado"); /* Adding an element to the array */
/* Displaying elements of the array */
for(var i=0; i < fruits.length; i++){
console.log(fruits[i]);
}
You can use the push method.
Array.prototype.append = function(destArray){
destArray = destArray || [];
this.push.call(this, ...destArray);
return this;
}
var arr = [1,2,5,67];
var arr1 = [7,4,7,8];
console.log(arr.append(arr1)); // [7, 4, 7, 8, 1, 4, 5, 67, 7]
console.log(arr.append("Hola")) // [1, 2, 5, 67, 7, 4, 7, 8, "H", "o", "l", "a"]
push() adds a new element to the end of an array.
pop() removes an element from the end of an array.
To append an object (such as a string or number) to an array, use:
array.push(toAppend);

efficient way to remove an object from an array of objects [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);

How to get item from multiple consecutive arrays

I am having a little difficuly coming up with a solution to my problem.
I am trying to get the item at an index of a collection of arrays. I cannot actually concatenate the arrays, they need to stay seperate.
Normally, to get the 3rd item from an array, you would do:
function getItemFromJustOneArray(index){
var my_array = [1,2,3,4,5,6];
return my_array[index];
}
getItemFromJustOneArray(2); // returns 3
However, I have a bunch of arrays (could be any amount of arrays) and these arrays cannot be merged into one.
function getItemFromMultipleArrays(index){
var array1 = [1,2];
var array2 = [3,4,5];
var array3 = [6];
// I cannot use concat (or similar) to merge the arrays,
// they need to stay seperate
// also, could be 3 arrays, but could also be 1, or 5...
// return 3;
}
getItemFromMultipleArrays(2); // SHOULD RETURN 3
I have tried a bunch of lines that loops over the array, but I cannot really get a working solution.
Does someone know an elegant solution to this problem?
Nest all the arrays in another array. Then loop over that array, decrementing index by each array's length until it's within the length of the current element. Then you can return the appropriate element of that nested array.
function getItemFromMultipleArrays(index) {
var array1 = [1, 2];
var array2 = [3, 4, 5];
var array3 = [6];
var all_arrays = [array1, array2, array3];
var i;
for (i = 0; i < all_arrays.length && index >= all_arrays[i].length; i++) {
index -= all_arrays[i].length;
}
if (i < all_arrays.length) {
return all_arrays[i][index];
}
}
console.log(getItemFromMultipleArrays(2)); // SHOULD RETURN 3
Why not spread the arrays to a new one and use the index for the value?
function getItemFromMultipleArrays(index) {
const
array1 = [1, 2],
array2 = [3, 4, 5],
array3 = [6];
return [...array1, ...array2, ...array3][index];
}
console.log(getItemFromMultipleArrays(2)); // 3
Another approach by using an offset for iterating arrays.
function getItemFromMultipleArrays(index) {
const
array1 = [1, 2],
array2 = [3, 4, 5],
array3 = [6],
temp = [array1, array2, array3];
let j = 0;
while (index >= temp[j].length) index -= temp[j++].length;
return temp[j][index];
}
console.log(getItemFromMultipleArrays(2)); // 3
console.log(getItemFromMultipleArrays(5)); // 6
this should do it, just copying all the arrays into a "big" one and accessing it (added a helping function)
// this function takes any amount of arrays and returns a new
// "concatted" array without affecting the original ones.
function connectArrays(...arrays) {
return [...arrays.flat()];
}
function getItemFromMultipleArrays(index) {
var array1 = [1,2];
var array2 = [3,4,5];
var array3 = [6];
var allArrays = connectArrays(array1, array2, array3);
return allArrays[index];
}
getItemFromMultipleArrays(2); // SHOULD RETURN 3

What is the most efficient way to check if n arrays are the same length?

What is the most efficient way to check if n arrays are the same length in JavaScript?
Use Array.every with the length accessor.
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const array3 = [7, 8, 9, 0];
const firstLength = array1.length;
const allSameLength = [array2, array3]
.every(({length}) => length === firstLength);
console.log(allSameLength);
If the arrays whose lengths you want to examine are stored inside a "parent" array, then you can simply use every to check whether the length of the iterated array is the same as the length of the first one.
Example:
const array = [
["a", "b", "c"],
[1, 2, 3],
[[1, 2], 3, "f"]
];
const equal = array.every((val, i, arr) => val.length === arr[0].length);
console.log(equal);
Initialize an array of the arrays, apply the .length function to each element using map and then return whether or not the min and max of the array are equal.
You could also just store a variable that is the first array length you come across and then check to see if each of the arrays is the same length as that array.
I'm not sure if the min/max functions in JS sort or do an O(n) search through the array, but the second method will definitely be O(n).
Edit: I imagine the 'every' function is also O(n) but I'm not sure (I would be very surprised if it is better and less surprised if it is worse).
As soon as you find one array with a different length than the first one, you know they're not all the same length. Otherwise you just have to check .length for every array to know for sure, so there isn't going to be anything faster than that.
function checkLengths() {
var len = arguments[0].length;
for(var i = 1; i < arguments.length; i++) {
if(arguments[i].length != len) {
return false;
}
}
return true;
}
var arr1 = [0, 1, 2];
var arr2 = ['lala', 'ayy', 'whatup'];
var arr3 = ['what in the worlddddd'];
console.log('Same lengths:', checkLengths(arr1, arr2));
console.log('Same lengths:', checkLengths(arr1, arr2, arr3));
I wouldn't expect other answers to be significantly different...

Only specific 'columns' from a 2d javascript array

I have an array in js:
myArray = [['1','2','3'],['4','5','6'],['7','8','9']];
How can I produce an array like this:
myAlteredArray = [['2','3'],['5','6'],['8','9']];
I basically want to exclude the first column out of the array.
Quick solution
The easiest way to do this would be to use map and slice.
var subsections = myArray.map(function (subarray) {
return subarray.slice(1)
})
You could also manipulate the subsections in any way you want by doing the following:
var subsections = myArray.map(function (subarray) {
var subsection = subarray.slice(1)
subsection[1] = parseInt(subsection[1], 10) // parse index 1 in base 10
return subsection
})
Array.prototype.map
myArray.map(callback) executes callback on each element in myArray and returns a new array made up of all the return values. For example:
[1, 2, 3].map(function (number) { return 10 - number })
would return [9, 8, 7] and leave the original array unchanged.
Array.prototype.slice
myArray.slice(start, [end]) will return a subsection of myArray in a new array. If you only pass start, end is assumed to be the end of the array. For example:
['dogs', 'cats', 'fish', 'lizards'].slice(2) == ['fish', 'lizards']
['dogs', 'cats', 'fish', 'lizards'].slice(1, 3) == ['cats', 'fish']
Fun fact: .slice() works on strings too!
You can do it like this, but note that this will alter original array:
myArray = [['1','2','3'],['4','5','6'],['7','8','9']];
myArray.filter(function(i){
return i.shift();
});
console.log(myArray);//logs [["2", "3"], ["5", "6"], ["8", "9"]]
var myArray = [['1','2','3'],['4','5','6'],['7','8','9']];
var filteredArray = myArray.map(function(currArray,v){
return currArray.slice(1);
})
console.log(filteredArray);
You should iterate through the array and use the slice function in each subarray to extract the first element.
var myArray = [['1','2','3'],['4','5','6'],['7','8','9']];
for (var i = arr.length - 1; i >= 0; i--) {
arr[i] = arr.slice(1);
}

Categories

Resources