How to Remove Element from an Array in JavaScript

How can I remove a specific item from an array?

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);

How to remove item from array by value?

This can be a global function or a method of a custom object, if you aren't allowed to add to native prototypes. It removes all of the items from the array that match any of the arguments.

Array.prototype.remove = function() {
var what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
};

var ary = ['three', 'seven', 'eleven'];

ary.remove('seven');

/* returned value: (Array)
three,eleven
*/

To make it a global-

function removeA(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
var ary = ['three', 'seven', 'eleven'];
removeA(ary, 'seven');

/* returned value: (Array)
three,eleven
*/

And to take care of IE8 and below-

if(!Array.prototype.indexOf) {
Array.prototype.indexOf = function(what, i) {
i = i || 0;
var L = this.length;
while (i < L) {
if(this[i] === what) return i;
++i;
}
return -1;
};
}

How to remove element from an array in JavaScript?

For a more flexible solution, use the splice() function. It allows you to remove any item in an Array based on Index Value:

var indexToRemove = 0;
var numberToRemove = 1;

arr.splice(indexToRemove, numberToRemove);

What is the cleanest way to remove an element from an immutable array in JS?

You can use a combination of spread and Array#slice:

const arr = ['a', 'b', 'c', 'd', 'e'];
const indexToRemove = 2; // the 'c'
const result = [...arr.slice(0, indexToRemove), ...arr.slice(indexToRemove + 1)];
console.log(result);

Deleting array elements in JavaScript - delete vs splice

delete will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined:

> myArray = ['a', 'b', 'c', 'd']
["a", "b", "c", "d"]
> delete myArray[0]
true
> myArray[0]
undefined

Note that it is not in fact set to the value undefined, rather the property is removed from the array, making it appear undefined. The Chrome dev tools make this distinction clear by printing empty when logging the array.

> myArray[0]
undefined
> myArray
[empty, "b", "c", "d"]

myArray.splice(start, deleteCount) actually removes the element, reindexes the array, and changes its length.

> myArray = ['a', 'b', 'c', 'd']
["a", "b", "c", "d"]
> myArray.splice(0, 2)
["a", "b"]
> myArray
["c", "d"]

How can I remove an array element by index,using javaScript?

You can use splice to do the same. Syntax = array.splice(start_index, no_of_elements_to_remove) Following is the command:

const fruits = ["mango","apple","pine","berry"]; // returns mutated array
const removed = fruits.splice(2, 1); // returns array of removed items
console.log('fruits', fruits);
console.log('removed', removed);

Remove array element based on object property

One possibility:

myArray = myArray.filter(function( obj ) {
return obj.field !== 'money';
});

Please note that filter creates a new array. Any other variables referring to the original array would not get the filtered data although you update your original variable myArray with the new reference. Use with caution.

Remove Object from Array using JavaScript

You can use several methods to remove item(s) from an Array:

//1
someArray.shift(); // first element removed
//2
someArray = someArray.slice(1); // first element removed
//3
someArray.splice(0, 1); // first element removed
//4
someArray.pop(); // last element removed
//5
someArray = someArray.slice(0, someArray.length - 1); // last element removed
//6
someArray.length = someArray.length - 1; // last element removed

If you want to remove element at position x, use:

someArray.splice(x, 1);

Or

someArray = someArray.slice(0, x).concat(someArray.slice(-x));

Reply to the comment of @chill182: you can remove one or more elements from an array using Array.filter, or Array.splice combined with Array.findIndex (see MDN).

See this Stackblitz project or the snippet below:

// non destructive filter > noJohn = John removed, but someArray will not change
let someArray = getArray();
let noJohn = someArray.filter( el => el.name !== "John" );
log(`let noJohn = someArray.filter( el => el.name !== "John")`,
`non destructive filter [noJohn] =`, format(noJohn));
log(`**someArray.length ${someArray.length}`);

// destructive filter/reassign John removed > someArray2 =
let someArray2 = getArray();
someArray2 = someArray2.filter( el => el.name !== "John" );
log("",
`someArray2 = someArray2.filter( el => el.name !== "John" )`,
`destructive filter/reassign John removed [someArray2] =`,
format(someArray2));
log(`**someArray2.length after filter ${someArray2.length}`);

// destructive splice /w findIndex Brian remains > someArray3 =
let someArray3 = getArray();
someArray3.splice(someArray3.findIndex(v => v.name === "Kristian"), 1);
someArray3.splice(someArray3.findIndex(v => v.name === "John"), 1);
log("",
`someArray3.splice(someArray3.findIndex(v => v.name === "Kristian"), 1),`,
`destructive splice /w findIndex Brian remains [someArray3] =`,
format(someArray3));
log(`**someArray3.length after splice ${someArray3.length}`);

// if you're not sure about the contents of your array,
// you should check the results of findIndex first
let someArray4 = getArray();
const indx = someArray4.findIndex(v => v.name === "Michael");
someArray4.splice(indx, indx >= 0 ? 1 : 0);
log("", `someArray4.splice(indx, indx >= 0 ? 1 : 0)`,
`check findIndex result first [someArray4] = (nothing is removed)`,
format(someArray4));
log(`**someArray4.length (should still be 3) ${someArray4.length}`);

// -- helpers --
function format(obj) {
return JSON.stringify(obj, null, " ");
}

function log(...txt) {
document.querySelector("pre").textContent += `${txt.join("\n")}\n`
}

function getArray() {
return [ {name: "Kristian", lines: "2,5,10"},
{name: "John", lines: "1,19,26,96"},
{name: "Brian", lines: "3,9,62,36"} ];
}
<pre>
**Results**

</pre>


Related Topics



Leave a reply



Submit