How can I remove an object from an array?
I wish to remove the object that includes name Kristian from someArray. For example:
someArray = [{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"}];
I want to achieve:
someArray = [{name:"John", lines:"1,19,26,96"}];
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>
The clean solution would be to use Array.filter:
var filtered = someArray.filter(function(el) { return el.Name != "Kristian"; });
The problem with this is that it does not work on IE < 9. However, you can include code from a Javascript library (e.g. underscore.js) that implements this for any browser.
I recommend using lodash.js or sugar.js for common tasks like this:
// lodash.js
someArray = _.reject(someArray, function(el) { return el.Name === "Kristian"; });
// sugar.js
someArray.remove(function(el) { return el.Name === "Kristian"; });
in most projects, having a set of helper methods that is provided by libraries like these is quite useful.
ES2015
let someArray = [
{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"},
{name:"Kristian", lines:"2,58,160"},
{name:"Felix", lines:"1,19,26,96"}
];
someArray = someArray.filter(person => person.name != 'John');
It will remove John!
How about this?
$.each(someArray, function(i){
if(someArray[i].name === 'Kristian') {
someArray.splice(i,1);
return false;
}
});
Your "array" as shown is invalid JavaScript syntax. Curly brackets {} are for objects with property name/value pairs, but square brackets [] are for arrays - like so:
someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];
In that case, you can use the .splice() method to remove an item. To remove the first item (index 0), say:
someArray.splice(0,1);
// someArray = [{name:"John", lines:"1,19,26,96"}];
If you don't know the index but want to search through the array to find the item with name "Kristian" to remove you could to this:
for (var i =0; i < someArray.length; i++)
if (someArray[i].name === "Kristian") {
someArray.splice(i,1);
break;
}
EDIT: I just noticed your question is tagged with "jQuery", so you could try the $.grep() method:
someArray = $.grep(someArray,
function(o,i) { return o.name === "Kristian"; },
true);
You could use array.filter().
e.g.
someArray = [{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"}];
someArray = someArray.filter(function(returnableObjects){
return returnableObjects.name !== 'Kristian';
});
//someArray will now be = [{name:"John", lines:"1,19,26,96"}];
Arrow functions:
someArray = someArray.filter(x => x.name !== 'Kristian')
I have made a dynamic function takes the objects Array, Key and value and returns the same array after removing the desired object:
function removeFunction (myObjects,prop,valu)
{
return myObjects.filter(function (val) {
return val[prop] !== valu;
});
}
Full Example: DEMO
var obj = {
"results": [
{
"id": "460",
"name": "Widget 1",
"loc": "Shed"
}, {
"id": "461",
"name": "Widget 2",
"loc": "Kitchen"
}, {
"id": "462",
"name": "Widget 3",
"loc": "bath"
}
]
};
function removeFunction (myObjects,prop,valu)
{
return myObjects.filter(function (val) {
return val[prop] !== valu;
});
}
console.log(removeFunction(obj.results,"id","460"));
This is a function that works for me:
function removeFromArray(array, value) {
var idx = array.indexOf(value);
if (idx !== -1) {
array.splice(idx, 1);
}
return array;
}
You could also try doing something like this:
var myArray = [{'name': 'test'}, {'name':'test2'}];
var myObject = {'name': 'test'};
myArray.splice(myArray.indexOf(myObject),1);
const someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];
We get the index of the object which have name property value as "Kristian"
const index = someArray.findIndex(key => key.name === "Kristian");
console.log(index); // 0
By using splice function we are removing the object which have the name property value as "Kristian"
someArray.splice(index,1);
console.log(someArray); // [{name:"John", lines:"1,19,26,96"}]
someArray = jQuery.grep(someArray , function (value) {
return value.name != 'Kristian';
});
Here is an example with map and splice
const arrayObject = [
{ name: "name1", value: "value1" },
{ name: "name2", value: "value2" },
{ name: "name3", value: "value3" },
];
let index = arrayObject.map((item) => item.name).indexOf("name1");
if (index > -1) {
arrayObject.splice(index, 1);
console.log("Result", arrayObject);
}
Output
Result [
{
"name": "name2",
"value": "value2"
},
{
"name": "name3",
"value": "value3"
}
]
Use splice function on arrays. Specify the position of the start element and the length of the subsequence you want to remove.
someArray.splice(pos, 1);
Vote for the UndercoreJS for simple work with arrays.
_.without() function helps to remove an element:
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
=> [2, 3, 4]
Performance
Today 2021.01.27 I perform tests on MacOs HighSierra 10.13.6 on Chrome v88, Safari v13.1.2 and Firefox v84 for chosen solutions.
Results
For all browsers:
fast/fastest solutions when element not exists: A and B
fast/fastest solutions for big arrays: C
fast/fastest solutions for big arrays when element exists: H
quite slow solutions for small arrays: F and G
quite slow solutions for big arrays: D, E and F
Details
I perform 4 tests cases:
small array (10 elements) and element exists - you can run it HERE
small array (10 elements) and element NOT exists - you can run it HERE
big array (milion elements) and element exists - you can run it HERE
big array (milion elements) and element NOT exists - you can run it HERE
Below snippet presents differences between solutions
A
B
C
D
E
F
G
H
I
function A(arr, name) {
let idx = arr.findIndex(o => o.name==name);
if(idx>=0) arr.splice(idx, 1);
return arr;
}
function B(arr, name) {
let idx = arr.findIndex(o => o.name==name);
return idx<0 ? arr : arr.slice(0,idx).concat(arr.slice(idx+1,arr.length));
}
function C(arr, name) {
let idx = arr.findIndex(o => o.name==name);
delete arr[idx];
return arr;
}
function D(arr, name) {
return arr.filter(el => el.name != name);
}
function E(arr, name) {
let result = [];
arr.forEach(o => o.name==name || result.push(o));
return result;
}
function F(arr, name) {
return _.reject(arr, el => el.name == name);
}
function G(arr, name) {
let o = arr.find(o => o.name==name);
return _.without(arr,o);
}
function H(arr, name) {
$.each(arr, function(i){
if(arr[i].name === 'Kristian') {
arr.splice(i,1);
return false;
}
});
return arr;
}
function I(arr, name) {
return $.grep(arr,o => o.name!=name);
}
// Test
let test1 = [
{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"},
];
let test2 = [
{name:"John3", lines:"1,19,26,96"},
{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"},
{name:"Joh2", lines:"1,19,26,96"},
];
let test3 = [
{name:"John3", lines:"1,19,26,96"},
{name:"John", lines:"1,19,26,96"},
{name:"Joh2", lines:"1,19,26,96"},
];
console.log(`
Test1: original array from question
Test2: array with more data
Test3: array without element which we want to delete
`);
[A,B,C,D,E,F,G,H,I].forEach(f=> console.log(`
Test1 ${f.name}: ${JSON.stringify(f([...test1],"Kristian"))}
Test2 ${f.name}: ${JSON.stringify(f([...test2],"Kristian"))}
Test3 ${f.name}: ${JSON.stringify(f([...test3],"Kristian"))}
`));
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
This shippet only presents functions used in performance tests - it not perform tests itself!
And here are example results for chrome
With ES 6 arrow function
let someArray = [
{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"}
];
let arrayToRemove={name:"Kristian", lines:"2,5,10"};
someArray=someArray.filter((e)=>e.name !=arrayToRemove.name && e.lines!= arrayToRemove.lines)
Although this is probably not that appropriate for this situation I found out the other day that you can also use the delete keyword to remove an item from an array if you don't need to alter the size of the array e.g.
var myArray = [1,2,3];
delete myArray[1];
console.log(myArray[1]); //undefined
console.log(myArray.length); //3 - doesn't actually shrink the array down
Simplest solution would be to create a map that stores the indexes for each object by name, like this:
//adding to array
var newPerson = {name:"Kristian", lines:"2,5,10"}
someMap[ newPerson.name ] = someArray.length;
someArray.push( newPerson );
//deleting from the array
var index = someMap[ 'Kristian' ];
someArray.splice( index, 1 );
You can use map function also.
someArray = [{name:"Kristian", lines:"2,5,10"},{name:"John",lines:"1,19,26,96"}];
newArray=[];
someArray.map(function(obj, index){
if(obj.name !== "Kristian"){
newArray.push(obj);
}
});
someArray = newArray;
console.log(someArray);
If you want to remove all occurrences of a given object (based on some condition) then use the javascript splice method inside a for the loop.
Since removing an object would affect the array length, make sure to decrement the counter one step, so that length check remains intact.
var objArr=[{Name:"Alex", Age:62},
{Name:"Robert", Age:18},
{Name:"Prince", Age:28},
{Name:"Cesar", Age:38},
{Name:"Sam", Age:42},
{Name:"David", Age:52}
];
for(var i = 0;i < objArr.length; i ++)
{
if(objArr[i].Age > 20)
{
objArr.splice(i, 1);
i--; //re-adjust the counter.
}
}
The above code snippet removes all objects with age greater than 20.
This answer
for (var i =0; i < someArray.length; i++)
if (someArray[i].name === "Kristian") {
someArray.splice(i,1);
}
is not working for multiple records fulfilling the condition. If you have two such consecutive records, only the first one is removed, and the other one skipped. You have to use:
for (var i = someArray.length - 1; i>= 0; i--)
...
instead .
I guess the answers are very branched and knotted.
You can use the following path to remove an array object that matches the object given in the modern JavaScript jargon.
coordinates = [
{ lat: 36.779098444109145, lng: 34.57202827508546 },
{ lat: 36.778754712956506, lng: 34.56898128564454 },
{ lat: 36.777414146732426, lng: 34.57179224069215 }
];
coordinate = { lat: 36.779098444109145, lng: 34.57202827508546 };
removeCoordinate(coordinate: Coordinate): Coordinate {
const found = this.coordinates.find((coordinate) => coordinate == coordinate);
if (found) {
this.coordinates.splice(found, 1);
}
return coordinate;
}
There seems to be an error in your array syntax so assuming you mean an array as opposed to an object, Array.splice is your friend here:
someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];
someArray.splice(1,1)
Use javascript's splice() function.
This may help: http://www.w3schools.com/jsref/jsref_splice.asp
You could also use some:
someArray = [{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"}];
someArray.some(item => {
if(item.name === "Kristian") // Case sensitive, will only remove first instance
someArray.splice(someArray.indexOf(item),1)
})
This is what I use.
Array.prototype.delete = function(pos){
this[pos] = undefined;
var len = this.length - 1;
for(var a = pos;a < this.length - 1;a++){
this[a] = this[a+1];
}
this.pop();
}
Then it is as simple as saying
var myArray = [1,2,3,4,5,6,7,8,9];
myArray.delete(3);
Replace any number in place of three. After the expected output should be:
console.log(myArray); //Expected output 1,2,3,5,6,7,8,9
splice(i, 1) where i is the incremental index of the array will remove the object.
But remember splice will also reset the array length so watch out for 'undefined'. Using your example, if you remove 'Kristian', then in the next execution within the loop, i will be 2 but someArray will be a length of 1, therefore if you try to remove "John" you will get an "undefined" error. One solution to this albeit not elegant is to have separate counter to keep track of index of the element to be removed.
Returns only objects from the array whose property name is not "Kristian"
var noKristianArray = $.grep(someArray, function (el) { return el.name!= "Kristian"; });
Demo:
var someArray = [
{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"},
{name:"Kristian", lines:"2,58,160"},
{name:"Felix", lines:"1,19,26,96"}
];
var noKristianArray = $.grep(someArray, function (el) { return el.name!= "Kristian"; });
console.log(noKristianArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This Concepts using Kendo Grid
var grid = $("#addNewAllergies").data("kendoGrid");
var selectedItem = SelectedCheckBoxList;
for (var i = 0; i < selectedItem.length; i++) {
if(selectedItem[i].boolKendoValue==true)
{
selectedItem.length= 0;
}
}
Related
var listToDelete = ['abc', 'efg'];
var arrayOfObjects = [{id:'abc',name:'oh'}, // delete me
{id:'efg',name:'em'}, // delete me
{id:'hij',name:'ge'}] // all that should remain
How do I remove an object from the array by matching object property?
Only native JavaScript please.
I am having trouble using splice because length diminishes with each deletion.
Using clone and splicing on orignal index still leaves you with the problem of diminishing length.
I assume you used splice something like this?
for (var i = 0; i < arrayOfObjects.length; i++) {
var obj = arrayOfObjects[i];
if (listToDelete.indexOf(obj.id) !== -1) {
arrayOfObjects.splice(i, 1);
}
}
All you need to do to fix the bug is decrement i for the next time around, then (and looping backwards is also an option):
for (var i = 0; i < arrayOfObjects.length; i++) {
var obj = arrayOfObjects[i];
if (listToDelete.indexOf(obj.id) !== -1) {
arrayOfObjects.splice(i, 1);
i--;
}
}
To avoid linear-time deletions, you can write array elements you want to keep over the array:
var end = 0;
for (var i = 0; i < arrayOfObjects.length; i++) {
var obj = arrayOfObjects[i];
if (listToDelete.indexOf(obj.id) === -1) {
arrayOfObjects[end++] = obj;
}
}
arrayOfObjects.length = end;
and to avoid linear-time lookups in a modern runtime, you can use a hash set:
const setToDelete = new Set(listToDelete);
let end = 0;
for (let i = 0; i < arrayOfObjects.length; i++) {
const obj = arrayOfObjects[i];
if (setToDelete.has(obj.id)) {
arrayOfObjects[end++] = obj;
}
}
arrayOfObjects.length = end;
which can be wrapped up in a nice function:
const filterInPlace = (array, predicate) => {
let end = 0;
for (let i = 0; i < array.length; i++) {
const obj = array[i];
if (predicate(obj)) {
array[end++] = obj;
}
}
array.length = end;
};
const toDelete = new Set(['abc', 'efg']);
const arrayOfObjects = [{id: 'abc', name: 'oh'},
{id: 'efg', name: 'em'},
{id: 'hij', name: 'ge'}];
filterInPlace(arrayOfObjects, obj => !toDelete.has(obj.id));
console.log(arrayOfObjects);
If you don’t need to do it in place, that’s Array#filter:
const toDelete = new Set(['abc', 'efg']);
const newArray = arrayOfObjects.filter(obj => !toDelete.has(obj.id));
You can remove an item by one of its properties without using any 3rd party libs like this:
var removeIndex = array.map(item => item.id).indexOf("abc");
~removeIndex && array.splice(removeIndex, 1);
With lodash/underscore:
If you want to modify the existing array itself, then we have to use splice. Here is the little better/readable way using findWhere of underscore/lodash:
var items= [{id:'abc',name:'oh'}, // delete me
{id:'efg',name:'em'},
{id:'hij',name:'ge'}];
items.splice(_.indexOf(items, _.findWhere(items, { id : "abc"})), 1);
With ES5 or higher
(without lodash/underscore)
With ES5 onwards we have findIndex method on array, so its easier without lodash/underscore
items.splice(items.findIndex(function(i){
return i.id === "abc";
}), 1);
(ES5 is supported in almost all morden browsers)
About findIndex, and its Browser compatibility
To delete an object by it's id in given array;
const hero = [{'id' : 1, 'name' : 'hero1'}, {'id': 2, 'name' : 'hero2'}];
//remove hero1
const updatedHero = hero.filter(item => item.id !== 1);
findIndex works for modern browsers:
var myArr = [{id:'a'},{id:'myid'},{id:'c'}];
var index = myArr.findIndex(function(o){
return o.id === 'myid';
})
if (index !== -1) myArr.splice(index, 1);
Check this out using Set and ES5 filter.
let result = arrayOfObjects.filter( el => (-1 == listToDelete.indexOf(el.id)) );
console.log(result);
Here is JsFiddle:
https://jsfiddle.net/jsq0a0p1/1/
If you just want to remove it from the existing array and not create a new one, try:
var items = [{Id: 1},{Id: 2},{Id: 3}];
items.splice(_.indexOf(items, _.find(items, function (item) { return item.Id === 2; })), 1);
Loop in reverse by decrementing i to avoid the problem:
for (var i = arrayOfObjects.length - 1; i >= 0; i--) {
var obj = arrayOfObjects[i];
if (listToDelete.indexOf(obj.id) !== -1) {
arrayOfObjects.splice(i, 1);
}
}
Or use filter:
var newArray = arrayOfObjects.filter(function(obj) {
return listToDelete.indexOf(obj.id) === -1;
});
Only native JavaScript please.
As an alternative, more "functional" solution, working on ECMAScript 5, you could use:
var listToDelete = ['abc', 'efg'];
var arrayOfObjects = [{id:'abc',name:'oh'}, // delete me
{id:'efg',name:'em'}, // delete me
{id:'hij',name:'ge'}]; // all that should remain
arrayOfObjects.reduceRight(function(acc, obj, idx) {
if (listToDelete.indexOf(obj.id) > -1)
arrayOfObjects.splice(idx,1);
}, 0); // initial value set to avoid issues with the first item and
// when the array is empty.
console.log(arrayOfObjects);
[ { id: 'hij', name: 'ge' } ]
According to the definition of 'Array.prototype.reduceRight' in ECMA-262:
reduceRight does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn.
So this is a valid usage of reduceRight.
var arrayOfObjects = [{id:'abc',name:'oh'}, // delete me
{id:'efg',name:'em'}, // delete me
{id:'hij',name:'ge'}] // all that should remain
as per your answer will be like this. when you click some particular object send the index in the param for the delete me function. This simple code will work like charm.
function deleteme(i){
if (i > -1) {
arrayOfObjects.splice(i, 1);
}
}
If you like short and self descriptive parameters or if you don't want to use splice and go with a straight forward filter or if you are simply a SQL person like me:
function removeFromArrayOfHash(p_array_of_hash, p_key, p_value_to_remove){
return p_array_of_hash.filter((l_cur_row) => {return l_cur_row[p_key] != p_value_to_remove});
}
And a sample usage:
l_test_arr =
[
{
post_id: 1,
post_content: "Hey I am the first hash with id 1"
},
{
post_id: 2,
post_content: "This is item 2"
},
{
post_id: 1,
post_content: "And I am the second hash with id 1"
},
{
post_id: 3,
post_content: "This is item 3"
},
];
l_test_arr = removeFromArrayOfHash(l_test_arr, "post_id", 2); // gives both of the post_id 1 hashes and the post_id 3
l_test_arr = removeFromArrayOfHash(l_test_arr, "post_id", 1); // gives only post_id 3 (since 1 was removed in previous line)
with filter & indexOf
withLodash = _.filter(arrayOfObjects, (obj) => (listToDelete.indexOf(obj.id) === -1));
withoutLodash = arrayOfObjects.filter(obj => listToDelete.indexOf(obj.id) === -1);
with filter & includes
withLodash = _.filter(arrayOfObjects, (obj) => (!listToDelete.includes(obj.id)))
withoutLodash = arrayOfObjects.filter(obj => !listToDelete.includes(obj.id));
You can use filter. This method always returns the element if the condition is true. So if you want to remove by id you must keep all the element that doesn't match with the given id. Here is an example:
arrayOfObjects = arrayOfObjects.filter(obj => obj.id != idToRemove)
Incorrect way
First of all, any answer that suggests to use filter does not actually remove the item. Here is a quick test:
var numbers = [1, 2, 2, 3];
numbers.filter(x => x === 2);
console.log(numbers.length);
In the above, the numbers array will stay intact (nothing will be removed). The filter method returns a new array with all the elements that satisfy the condition x === 2 but the original array is left intact.
Sure you can do this:
var numbers = [1, 2, 2, 3];
numbers = numbers.filter(x => x === 2);
console.log(numbers.length);
But that is simply assigning a new array to numbers.
Correct way to remove items from array
One of the correct ways, there are more than 1, is to do it as following. Please keep in mind, the example here intentionally has duplicated items so the removal of duplicates can be taken into consideration.
var numbers = [1, 2, 2, 3];
// Find all items you wish to remove
// If array has objects, then change condition to x.someProperty === someValue
var numbersToRemove = numbers.filter(x => x === 2);
// Now remove them
numbersToRemove.forEach(x => numbers.splice(numbers.findIndex(n => n === x), 1));
// Now check (this is obviously just to test)
console.log(numbers.length);
console.log(numbers);
Now you will notice length returns 2 indicating only numbers 1 and 3 are remaining in the array.
In your case
To specifically answer your question which is this:
var listToDelete = ['abc', 'efg'];
var arrayOfObjects = [{id:'abc',name:'oh'}, // delete me
{id:'efg',name:'em'}, // delete me
{id:'hij',name:'ge'}] // all that should remain
Here is the answer:
listToDelete.forEach(x => arrayOfObjects.splice(arrayOfObjects.findIndex(n => n.id === x), 1));
var listToDelete = ['abc', 'efg'];
var arrayOfObjects = [{id:'abc',name:'oh'}, // delete me
{id:'efg',name:'em'}, // delete me
{id:'hij',name:'ge'}] // all that should remain
var result = arrayOfObjects.filter(object => !listToDelete.some(toDelete => toDelete === object.id));
console.log(result);
I have been trying several approaches on how to find an object in an array, where ID = var, and if found, remove the object from the array and return the new array of objects.
Data:
[
{"id":"88","name":"Lets go testing"},
{"id":"99","name":"Have fun boys and girls"},
{"id":"108","name":"You are awesome!"}
]
I'm able to search the array using jQuery $grep;
var id = 88;
var result = $.grep(data, function(e){
return e.id == id;
});
But how can I delete the entire object when id == 88, and return data like the following?
Data:
[
{"id":"99", "name":"Have fun boys and girls"},
{"id":"108", "name":"You are awesome!"}
]
Here is a solution if you are not using jQuery:
myArray = myArray.filter(function( obj ) {
return obj.id !== id;
});
I can grep the array for the id, but how can I delete the entire object where id == 88
Simply filter by the opposite predicate:
var data = $.grep(data, function(e){
return e.id != id;
});
You can simplify this, and there isn't really any need for using jQuery here.
var id = 88;
for(var i = 0; i < data.length; i++) {
if(data[i].id == id) {
data.splice(i, 1);
break;
}
}
Just iterate through the list, find the matching id, splice, and then break to exit your loop.
There's a new method to do this in ES6/2015 using findIndex and the array spread operator:
const index = data.findIndex(obj => obj.id === id);
const newData = [
...data.slice(0, index),
...data.slice(index + 1)
]
You can turn it into a function for later reuse like this:
function remove(array, key, value) {
const index = array.findIndex(obj => obj[key] === value);
return index >= 0 ? [
...array.slice(0, index),
...array.slice(index + 1)
] : array;
}
This way, you can remove items by different keys using one method (and if there's no object that meets the criteria, you get original array returned):
const newData = remove(data, "id", "88");
const newData2 = remove(data, "name", "You are awesome!");
Or you can put it on your Array.prototype:
Array.prototype.remove = function (key, value) {
const index = this.findIndex(obj => obj[key] === value);
return index >= 0 ? [
...this.slice(0, index),
...this.slice(index + 1)
] : this;
};
And use it this way:
const newData = data.remove("id", "88");
const newData2 = data.remove("name", "You are awesome!");
var items = [
{"id":"88","name":"Lets go testing"},
{"id":"99","name":"Have fun boys and girls"},
{"id":"108","name":"You are awesome!"}
];
If you are using jQuery, use jQuery.grep like this:
items = $.grep(items, function(item) {
return item.id !== '88';
});
// items => [{ id: "99" }, { id: "108" }]
Using ES5 Array.prototype.filter:
items = items.filter(function(item) {
return item.id !== '88';
});
// items => [{ id: "99" }, { id: "108" }]
Native ES6 solution:
const pos = data.findIndex(el => el.id === ID_TO_REMOVE);
if (pos >= 0)
data.splice(pos, 1);
If you know that the element is in the array for sure:
data.splice(data.findIndex(el => el.id === ID_TO_REMOVE), 1);
Prototype:
Array.prototype.removeByProp = function(prop,val) {
const pos = this.findIndex(x => x[prop] === val);
if (pos >= 0)
return this.splice(pos, 1);
};
// usage:
ar.removeByProp('id', ID_TO_REMOVE);
http://jsfiddle.net/oriadam/72kgprw5/
Note: this removes the item in-place. If you need a new array, use filter as mentioned in previous answers.
Assuming that ids are unique and you'll only have to remove the one element splice should do the trick:
var data = [
{"id":"88","name":"Lets go testing"},
{"id":"99","name":"Have fun boys and girls"},
{"id":"108","name":"You are awesome!"}
],
id = 88;
console.table(data);
$.each(data, function(i, el){
if (this.id == id){
data.splice(i, 1);
}
});
console.table(data);
const data = [
{"id":"88","name":"Lets go testing"},
{"id":"99","name":"Have fun boys and girls"},
{"id":"108","name":"You are awesome!"}
];
Here we get the index of the object whose value of the id is "88"
const index = data.findIndex(item => item.id === "88");
console.log(index); // 0
We use splice function to remove the specified object from data array
data.splice(index,1);
console.log(data); // [{"id":"99","name":"Have fun boys and girls"},{"id":"108","name":"You are awesome!"}]
Maybe you are looking for $.grep() function:
arr = [
{"id":"88","name":"Lets go testing"},
{"id":"99","name":"Have fun boys and girls"},
{"id":"108","name":"You are awesome!"}
];
id = 88;
arr = $.grep(arr, function(data, index) {
return data.id != id
});
I agree with the previous answers. A simple way if you want to find an object by id and remove it is simply like the below code:
var obj = JSON.parse(data);
var newObj = obj.filter(item => item.Id != 88);
Array.prototype.removeAt = function(id) {
for (var item in this) {
if (this[item].id == id) {
this.splice(item, 1);
return true;
}
}
return false;
}
This should do the trick, jsfiddle
sift is a powerful collection filter for operations like this and much more advanced ones. It works client side in the browser or server side in Node.js.
var collection = [
{"id":"88", "name":"Lets go testing"},
{"id":"99", "name":"Have fun boys and girls"},
{"id":"108", "name":"You are awesome!"}
];
var sifted = sift({id: {$not: 88}}, collection);
It supports filters like $in, $nin, $exists, $gte, $gt, $lte, $lt, $eq, $ne, $mod, $all, $and, $or, $nor, $not, $size, $type, and $regex, and strives to be API-compatible with MongoDB collection filtering.
Make sure you coerce the object id to an integer if you test for strict equality:
var result = $.grep(data, function(e, i) {
return +e.id !== id;
});
Demo
If you are using Underscore.js, it is easy to remove an object based on a key.
Example:
var temp1=[{id:1,name:"safeer"}, // Temporary array
{id:2,name:"jon"},
{id:3,name:"James"},
{id:4,name:"deepak"},
{id:5,name:"ajmal"}];
var id = _.pluck(temp1,'id'); // Get id array from temp1
var ids=[2,5,10]; // ids to be removed
var bool_ids=[];
_.each(ids,function(val){
bool_ids[val]=true;
});
_.filter(temp1,function(val){
return !bool_ids[val.id];
});
var listToDelete = ['abc', 'efg'];
var arrayOfObjects = [{id:'abc',name:'oh'}, // delete me
{id:'efg',name:'em'}, // delete me
{id:'hij',name:'ge'}] // all that should remain
How do I remove an object from the array by matching object property?
Only native JavaScript please.
I am having trouble using splice because length diminishes with each deletion.
Using clone and splicing on orignal index still leaves you with the problem of diminishing length.
I assume you used splice something like this?
for (var i = 0; i < arrayOfObjects.length; i++) {
var obj = arrayOfObjects[i];
if (listToDelete.indexOf(obj.id) !== -1) {
arrayOfObjects.splice(i, 1);
}
}
All you need to do to fix the bug is decrement i for the next time around, then (and looping backwards is also an option):
for (var i = 0; i < arrayOfObjects.length; i++) {
var obj = arrayOfObjects[i];
if (listToDelete.indexOf(obj.id) !== -1) {
arrayOfObjects.splice(i, 1);
i--;
}
}
To avoid linear-time deletions, you can write array elements you want to keep over the array:
var end = 0;
for (var i = 0; i < arrayOfObjects.length; i++) {
var obj = arrayOfObjects[i];
if (listToDelete.indexOf(obj.id) === -1) {
arrayOfObjects[end++] = obj;
}
}
arrayOfObjects.length = end;
and to avoid linear-time lookups in a modern runtime, you can use a hash set:
const setToDelete = new Set(listToDelete);
let end = 0;
for (let i = 0; i < arrayOfObjects.length; i++) {
const obj = arrayOfObjects[i];
if (setToDelete.has(obj.id)) {
arrayOfObjects[end++] = obj;
}
}
arrayOfObjects.length = end;
which can be wrapped up in a nice function:
const filterInPlace = (array, predicate) => {
let end = 0;
for (let i = 0; i < array.length; i++) {
const obj = array[i];
if (predicate(obj)) {
array[end++] = obj;
}
}
array.length = end;
};
const toDelete = new Set(['abc', 'efg']);
const arrayOfObjects = [{id: 'abc', name: 'oh'},
{id: 'efg', name: 'em'},
{id: 'hij', name: 'ge'}];
filterInPlace(arrayOfObjects, obj => !toDelete.has(obj.id));
console.log(arrayOfObjects);
If you don’t need to do it in place, that’s Array#filter:
const toDelete = new Set(['abc', 'efg']);
const newArray = arrayOfObjects.filter(obj => !toDelete.has(obj.id));
You can remove an item by one of its properties without using any 3rd party libs like this:
var removeIndex = array.map(item => item.id).indexOf("abc");
~removeIndex && array.splice(removeIndex, 1);
With lodash/underscore:
If you want to modify the existing array itself, then we have to use splice. Here is the little better/readable way using findWhere of underscore/lodash:
var items= [{id:'abc',name:'oh'}, // delete me
{id:'efg',name:'em'},
{id:'hij',name:'ge'}];
items.splice(_.indexOf(items, _.findWhere(items, { id : "abc"})), 1);
With ES5 or higher
(without lodash/underscore)
With ES5 onwards we have findIndex method on array, so its easier without lodash/underscore
items.splice(items.findIndex(function(i){
return i.id === "abc";
}), 1);
(ES5 is supported in almost all morden browsers)
About findIndex, and its Browser compatibility
To delete an object by it's id in given array;
const hero = [{'id' : 1, 'name' : 'hero1'}, {'id': 2, 'name' : 'hero2'}];
//remove hero1
const updatedHero = hero.filter(item => item.id !== 1);
findIndex works for modern browsers:
var myArr = [{id:'a'},{id:'myid'},{id:'c'}];
var index = myArr.findIndex(function(o){
return o.id === 'myid';
})
if (index !== -1) myArr.splice(index, 1);
Check this out using Set and ES5 filter.
let result = arrayOfObjects.filter( el => (-1 == listToDelete.indexOf(el.id)) );
console.log(result);
Here is JsFiddle:
https://jsfiddle.net/jsq0a0p1/1/
If you just want to remove it from the existing array and not create a new one, try:
var items = [{Id: 1},{Id: 2},{Id: 3}];
items.splice(_.indexOf(items, _.find(items, function (item) { return item.Id === 2; })), 1);
Loop in reverse by decrementing i to avoid the problem:
for (var i = arrayOfObjects.length - 1; i >= 0; i--) {
var obj = arrayOfObjects[i];
if (listToDelete.indexOf(obj.id) !== -1) {
arrayOfObjects.splice(i, 1);
}
}
Or use filter:
var newArray = arrayOfObjects.filter(function(obj) {
return listToDelete.indexOf(obj.id) === -1;
});
Only native JavaScript please.
As an alternative, more "functional" solution, working on ECMAScript 5, you could use:
var listToDelete = ['abc', 'efg'];
var arrayOfObjects = [{id:'abc',name:'oh'}, // delete me
{id:'efg',name:'em'}, // delete me
{id:'hij',name:'ge'}]; // all that should remain
arrayOfObjects.reduceRight(function(acc, obj, idx) {
if (listToDelete.indexOf(obj.id) > -1)
arrayOfObjects.splice(idx,1);
}, 0); // initial value set to avoid issues with the first item and
// when the array is empty.
console.log(arrayOfObjects);
[ { id: 'hij', name: 'ge' } ]
According to the definition of 'Array.prototype.reduceRight' in ECMA-262:
reduceRight does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn.
So this is a valid usage of reduceRight.
var arrayOfObjects = [{id:'abc',name:'oh'}, // delete me
{id:'efg',name:'em'}, // delete me
{id:'hij',name:'ge'}] // all that should remain
as per your answer will be like this. when you click some particular object send the index in the param for the delete me function. This simple code will work like charm.
function deleteme(i){
if (i > -1) {
arrayOfObjects.splice(i, 1);
}
}
If you like short and self descriptive parameters or if you don't want to use splice and go with a straight forward filter or if you are simply a SQL person like me:
function removeFromArrayOfHash(p_array_of_hash, p_key, p_value_to_remove){
return p_array_of_hash.filter((l_cur_row) => {return l_cur_row[p_key] != p_value_to_remove});
}
And a sample usage:
l_test_arr =
[
{
post_id: 1,
post_content: "Hey I am the first hash with id 1"
},
{
post_id: 2,
post_content: "This is item 2"
},
{
post_id: 1,
post_content: "And I am the second hash with id 1"
},
{
post_id: 3,
post_content: "This is item 3"
},
];
l_test_arr = removeFromArrayOfHash(l_test_arr, "post_id", 2); // gives both of the post_id 1 hashes and the post_id 3
l_test_arr = removeFromArrayOfHash(l_test_arr, "post_id", 1); // gives only post_id 3 (since 1 was removed in previous line)
with filter & indexOf
withLodash = _.filter(arrayOfObjects, (obj) => (listToDelete.indexOf(obj.id) === -1));
withoutLodash = arrayOfObjects.filter(obj => listToDelete.indexOf(obj.id) === -1);
with filter & includes
withLodash = _.filter(arrayOfObjects, (obj) => (!listToDelete.includes(obj.id)))
withoutLodash = arrayOfObjects.filter(obj => !listToDelete.includes(obj.id));
You can use filter. This method always returns the element if the condition is true. So if you want to remove by id you must keep all the element that doesn't match with the given id. Here is an example:
arrayOfObjects = arrayOfObjects.filter(obj => obj.id != idToRemove)
Incorrect way
First of all, any answer that suggests to use filter does not actually remove the item. Here is a quick test:
var numbers = [1, 2, 2, 3];
numbers.filter(x => x === 2);
console.log(numbers.length);
In the above, the numbers array will stay intact (nothing will be removed). The filter method returns a new array with all the elements that satisfy the condition x === 2 but the original array is left intact.
Sure you can do this:
var numbers = [1, 2, 2, 3];
numbers = numbers.filter(x => x === 2);
console.log(numbers.length);
But that is simply assigning a new array to numbers.
Correct way to remove items from array
One of the correct ways, there are more than 1, is to do it as following. Please keep in mind, the example here intentionally has duplicated items so the removal of duplicates can be taken into consideration.
var numbers = [1, 2, 2, 3];
// Find all items you wish to remove
// If array has objects, then change condition to x.someProperty === someValue
var numbersToRemove = numbers.filter(x => x === 2);
// Now remove them
numbersToRemove.forEach(x => numbers.splice(numbers.findIndex(n => n === x), 1));
// Now check (this is obviously just to test)
console.log(numbers.length);
console.log(numbers);
Now you will notice length returns 2 indicating only numbers 1 and 3 are remaining in the array.
In your case
To specifically answer your question which is this:
var listToDelete = ['abc', 'efg'];
var arrayOfObjects = [{id:'abc',name:'oh'}, // delete me
{id:'efg',name:'em'}, // delete me
{id:'hij',name:'ge'}] // all that should remain
Here is the answer:
listToDelete.forEach(x => arrayOfObjects.splice(arrayOfObjects.findIndex(n => n.id === x), 1));
var listToDelete = ['abc', 'efg'];
var arrayOfObjects = [{id:'abc',name:'oh'}, // delete me
{id:'efg',name:'em'}, // delete me
{id:'hij',name:'ge'}] // all that should remain
var result = arrayOfObjects.filter(object => !listToDelete.some(toDelete => toDelete === object.id));
console.log(result);
This question already has answers here:
Simplest code for array intersection in javascript
(40 answers)
Closed 3 years ago.
I have two arrays, and I want to be able to compare the two and only return the values that match. For example both arrays have the value cat so that is what will be returned. I haven't found anything like this. What would be the best way to return similarities?
var array1 = ["cat", "sum","fun", "run"];
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];
//if value in array1 is equal to value in array2 then return match: cat
You can use :
const intersection = array1.filter(element => array2.includes(element));
Naturally, my approach was to loop through the first array once and check the index of each value in the second array. If the index is > -1, then push it onto the returned array.
Array.prototype.diff = function(arr2) {
var ret = [];
for(var i in this) {
if(arr2.indexOf(this[i]) > -1){
ret.push(this[i]);
}
}
return ret;
};
My solution doesn't use two loops like others do so it may run a bit faster. If you want to avoid using for..in, you can sort both arrays first to reindex all their values:
Array.prototype.diff = function(arr2) {
var ret = [];
this.sort();
arr2.sort();
for(var i = 0; i < this.length; i += 1) {
if(arr2.indexOf(this[i]) > -1){
ret.push(this[i]);
}
}
return ret;
};
Usage would look like:
var array1 = ["cat", "sum","fun", "run", "hut"];
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];
console.log(array1.diff(array2));
If you have an issue/problem with extending the Array prototype, you could easily change this to a function.
var diff = function(arr, arr2) {
And you'd change anywhere where the func originally said this to arr2.
I found a slight alteration on what #jota3 suggested worked perfectly for me.
var intersections = array1.filter(e => array2.indexOf(e) !== -1);
Hope this helps!
This function runs in O(n log(n) + m log(m)) compared to O(n*m) (as seen in the other solutions with loops/indexOf) which can be useful if you are dealing with lots of values.
However, because neither "a" > 1 nor "a" < 1, this only works for elements of the same type.
function intersect_arrays(a, b) {
var sorted_a = a.concat().sort();
var sorted_b = b.concat().sort();
var common = [];
var a_i = 0;
var b_i = 0;
while (a_i < a.length
&& b_i < b.length)
{
if (sorted_a[a_i] === sorted_b[b_i]) {
common.push(sorted_a[a_i]);
a_i++;
b_i++;
}
else if(sorted_a[a_i] < sorted_b[b_i]) {
a_i++;
}
else {
b_i++;
}
}
return common;
}
Example:
var array1 = ["cat", "sum", "fun", "hut"], //modified for additional match
array2 = ["bat", "cat", "dog", "sun", "hut", "gut"];
intersect_arrays(array1, array2);
>> ["cat", "hut"]
Loop through the second array each time you iterate over an element in the first array, then check for matches.
var array1 = ["cat", "sum", "fun", "run"],
array2 = ["bat", "cat", "dog", "sun", "hut", "gut"];
function getMatch(a, b) {
var matches = [];
for ( var i = 0; i < a.length; i++ ) {
for ( var e = 0; e < b.length; e++ ) {
if ( a[i] === b[e] ) matches.push( a[i] );
}
}
return matches;
}
getMatch(array1, array2); // ["cat"]
var array1 = [1, 2, 3, 4, 5, 6];
var array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var array3 = array2.filter(function(obj) {
return array1.indexOf(obj) !== -1;
});
You can use javascript function .find()
As it says in MDN, it will return the first value that is true. If such an element is found, find immediately returns the value of that element. Otherwise, find returns undefined.
var array1 = ["cat", "sum", "fun", "run", "cat"];
var array2 = ["bat", "cat", "dog", "sun", "hut", "gut"];
found = array1.find((val, index) => {
console.log('index', index) // Stops at 0
return array2.includes(val)
})
console.log(found)
Or use .filter(), which loops through every elements first, then give back the result to you.
var array1 = ["cat", "sum", "fun", "run", "cat"];
var array2 = ["bat", "cat", "dog", "sun", "hut", "gut"];
found = array1.filter((val, index) => {
console.log('index', index) // Stops at array1.length - 1
return array2.includes(val)
})
console.log(found)
use lodash
GLOBAL.utils = require('lodash')
var arr1 = ['first' , 'second'];
var arr2 = ['second '];
var result = utils.difference(arr1 , arr2);
console.log ( "result :" + result );
Libraries like underscore and lodash have a utility method called intersection to find matches in arrays passed in. Take a look at: http://underscorejs.org/#intersection
Done as a answer so I can do formatting...
This is the the process you need to go through. Looping through an array for the specifics.
create an empty array
loop through array1, element by element. {
loop through array2, element by element {
if array1.element == array2.element {
add to your new array
}
}
}
If your values are non-null strings or numbers, you can use an object as a dictionary:
var map = {}, result = [], i;
for (i = 0; i < array1.length; ++i) {
map[array1[i]] = 1;
}
for (i = 0; i < array2.length; ++i) {
if (map[array2[i]] === 1) {
result.push(array2[i]);
// avoid returning a value twice if it appears twice in array 2
map[array2[i]] = 0;
}
}
return result;
With some ES6:
let sortedArray = [];
firstArr.map((first) => {
sortedArray[defaultArray.findIndex(def => def === first)] = first;
});
sortedArray = sortedArray.filter(v => v);
This snippet also sorts the firstArr based on the order of the defaultArray
like:
let firstArr = ['apple', 'kiwi', 'banana'];
let defaultArray = ['kiwi', 'apple', 'pear'];
...
console.log(sortedArray);
// ['kiwi', 'apple'];
Iterate on array1 and find the indexof element present in array2.
var array1 = ["cat", "sum","fun", "run"];
var array2 = ["bat", "cat","sun", "hut", "gut"];
var str='';
for(var i=0;i<array1.length;i++){
if(array2.indexOf(array1[i]) != -1){
str+=array1[i]+' ';
};
}
console.log(str)
How can I remove an object from an array?
I wish to remove the object that includes name Kristian from someArray. For example:
someArray = [{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"}];
I want to achieve:
someArray = [{name:"John", lines:"1,19,26,96"}];
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>
The clean solution would be to use Array.filter:
var filtered = someArray.filter(function(el) { return el.Name != "Kristian"; });
The problem with this is that it does not work on IE < 9. However, you can include code from a Javascript library (e.g. underscore.js) that implements this for any browser.
I recommend using lodash.js or sugar.js for common tasks like this:
// lodash.js
someArray = _.reject(someArray, function(el) { return el.Name === "Kristian"; });
// sugar.js
someArray.remove(function(el) { return el.Name === "Kristian"; });
in most projects, having a set of helper methods that is provided by libraries like these is quite useful.
ES2015
let someArray = [
{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"},
{name:"Kristian", lines:"2,58,160"},
{name:"Felix", lines:"1,19,26,96"}
];
someArray = someArray.filter(person => person.name != 'John');
It will remove John!
How about this?
$.each(someArray, function(i){
if(someArray[i].name === 'Kristian') {
someArray.splice(i,1);
return false;
}
});
Your "array" as shown is invalid JavaScript syntax. Curly brackets {} are for objects with property name/value pairs, but square brackets [] are for arrays - like so:
someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];
In that case, you can use the .splice() method to remove an item. To remove the first item (index 0), say:
someArray.splice(0,1);
// someArray = [{name:"John", lines:"1,19,26,96"}];
If you don't know the index but want to search through the array to find the item with name "Kristian" to remove you could to this:
for (var i =0; i < someArray.length; i++)
if (someArray[i].name === "Kristian") {
someArray.splice(i,1);
break;
}
EDIT: I just noticed your question is tagged with "jQuery", so you could try the $.grep() method:
someArray = $.grep(someArray,
function(o,i) { return o.name === "Kristian"; },
true);
You could use array.filter().
e.g.
someArray = [{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"}];
someArray = someArray.filter(function(returnableObjects){
return returnableObjects.name !== 'Kristian';
});
//someArray will now be = [{name:"John", lines:"1,19,26,96"}];
Arrow functions:
someArray = someArray.filter(x => x.name !== 'Kristian')
I have made a dynamic function takes the objects Array, Key and value and returns the same array after removing the desired object:
function removeFunction (myObjects,prop,valu)
{
return myObjects.filter(function (val) {
return val[prop] !== valu;
});
}
Full Example: DEMO
var obj = {
"results": [
{
"id": "460",
"name": "Widget 1",
"loc": "Shed"
}, {
"id": "461",
"name": "Widget 2",
"loc": "Kitchen"
}, {
"id": "462",
"name": "Widget 3",
"loc": "bath"
}
]
};
function removeFunction (myObjects,prop,valu)
{
return myObjects.filter(function (val) {
return val[prop] !== valu;
});
}
console.log(removeFunction(obj.results,"id","460"));
This is a function that works for me:
function removeFromArray(array, value) {
var idx = array.indexOf(value);
if (idx !== -1) {
array.splice(idx, 1);
}
return array;
}
You could also try doing something like this:
var myArray = [{'name': 'test'}, {'name':'test2'}];
var myObject = {'name': 'test'};
myArray.splice(myArray.indexOf(myObject),1);
const someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];
We get the index of the object which have name property value as "Kristian"
const index = someArray.findIndex(key => key.name === "Kristian");
console.log(index); // 0
By using splice function we are removing the object which have the name property value as "Kristian"
someArray.splice(index,1);
console.log(someArray); // [{name:"John", lines:"1,19,26,96"}]
someArray = jQuery.grep(someArray , function (value) {
return value.name != 'Kristian';
});
Here is an example with map and splice
const arrayObject = [
{ name: "name1", value: "value1" },
{ name: "name2", value: "value2" },
{ name: "name3", value: "value3" },
];
let index = arrayObject.map((item) => item.name).indexOf("name1");
if (index > -1) {
arrayObject.splice(index, 1);
console.log("Result", arrayObject);
}
Output
Result [
{
"name": "name2",
"value": "value2"
},
{
"name": "name3",
"value": "value3"
}
]
Use splice function on arrays. Specify the position of the start element and the length of the subsequence you want to remove.
someArray.splice(pos, 1);
Vote for the UndercoreJS for simple work with arrays.
_.without() function helps to remove an element:
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
=> [2, 3, 4]
Performance
Today 2021.01.27 I perform tests on MacOs HighSierra 10.13.6 on Chrome v88, Safari v13.1.2 and Firefox v84 for chosen solutions.
Results
For all browsers:
fast/fastest solutions when element not exists: A and B
fast/fastest solutions for big arrays: C
fast/fastest solutions for big arrays when element exists: H
quite slow solutions for small arrays: F and G
quite slow solutions for big arrays: D, E and F
Details
I perform 4 tests cases:
small array (10 elements) and element exists - you can run it HERE
small array (10 elements) and element NOT exists - you can run it HERE
big array (milion elements) and element exists - you can run it HERE
big array (milion elements) and element NOT exists - you can run it HERE
Below snippet presents differences between solutions
A
B
C
D
E
F
G
H
I
function A(arr, name) {
let idx = arr.findIndex(o => o.name==name);
if(idx>=0) arr.splice(idx, 1);
return arr;
}
function B(arr, name) {
let idx = arr.findIndex(o => o.name==name);
return idx<0 ? arr : arr.slice(0,idx).concat(arr.slice(idx+1,arr.length));
}
function C(arr, name) {
let idx = arr.findIndex(o => o.name==name);
delete arr[idx];
return arr;
}
function D(arr, name) {
return arr.filter(el => el.name != name);
}
function E(arr, name) {
let result = [];
arr.forEach(o => o.name==name || result.push(o));
return result;
}
function F(arr, name) {
return _.reject(arr, el => el.name == name);
}
function G(arr, name) {
let o = arr.find(o => o.name==name);
return _.without(arr,o);
}
function H(arr, name) {
$.each(arr, function(i){
if(arr[i].name === 'Kristian') {
arr.splice(i,1);
return false;
}
});
return arr;
}
function I(arr, name) {
return $.grep(arr,o => o.name!=name);
}
// Test
let test1 = [
{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"},
];
let test2 = [
{name:"John3", lines:"1,19,26,96"},
{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"},
{name:"Joh2", lines:"1,19,26,96"},
];
let test3 = [
{name:"John3", lines:"1,19,26,96"},
{name:"John", lines:"1,19,26,96"},
{name:"Joh2", lines:"1,19,26,96"},
];
console.log(`
Test1: original array from question
Test2: array with more data
Test3: array without element which we want to delete
`);
[A,B,C,D,E,F,G,H,I].forEach(f=> console.log(`
Test1 ${f.name}: ${JSON.stringify(f([...test1],"Kristian"))}
Test2 ${f.name}: ${JSON.stringify(f([...test2],"Kristian"))}
Test3 ${f.name}: ${JSON.stringify(f([...test3],"Kristian"))}
`));
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
This shippet only presents functions used in performance tests - it not perform tests itself!
And here are example results for chrome
With ES 6 arrow function
let someArray = [
{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"}
];
let arrayToRemove={name:"Kristian", lines:"2,5,10"};
someArray=someArray.filter((e)=>e.name !=arrayToRemove.name && e.lines!= arrayToRemove.lines)
Although this is probably not that appropriate for this situation I found out the other day that you can also use the delete keyword to remove an item from an array if you don't need to alter the size of the array e.g.
var myArray = [1,2,3];
delete myArray[1];
console.log(myArray[1]); //undefined
console.log(myArray.length); //3 - doesn't actually shrink the array down
Simplest solution would be to create a map that stores the indexes for each object by name, like this:
//adding to array
var newPerson = {name:"Kristian", lines:"2,5,10"}
someMap[ newPerson.name ] = someArray.length;
someArray.push( newPerson );
//deleting from the array
var index = someMap[ 'Kristian' ];
someArray.splice( index, 1 );
You can use map function also.
someArray = [{name:"Kristian", lines:"2,5,10"},{name:"John",lines:"1,19,26,96"}];
newArray=[];
someArray.map(function(obj, index){
if(obj.name !== "Kristian"){
newArray.push(obj);
}
});
someArray = newArray;
console.log(someArray);
If you want to remove all occurrences of a given object (based on some condition) then use the javascript splice method inside a for the loop.
Since removing an object would affect the array length, make sure to decrement the counter one step, so that length check remains intact.
var objArr=[{Name:"Alex", Age:62},
{Name:"Robert", Age:18},
{Name:"Prince", Age:28},
{Name:"Cesar", Age:38},
{Name:"Sam", Age:42},
{Name:"David", Age:52}
];
for(var i = 0;i < objArr.length; i ++)
{
if(objArr[i].Age > 20)
{
objArr.splice(i, 1);
i--; //re-adjust the counter.
}
}
The above code snippet removes all objects with age greater than 20.
This answer
for (var i =0; i < someArray.length; i++)
if (someArray[i].name === "Kristian") {
someArray.splice(i,1);
}
is not working for multiple records fulfilling the condition. If you have two such consecutive records, only the first one is removed, and the other one skipped. You have to use:
for (var i = someArray.length - 1; i>= 0; i--)
...
instead .
I guess the answers are very branched and knotted.
You can use the following path to remove an array object that matches the object given in the modern JavaScript jargon.
coordinates = [
{ lat: 36.779098444109145, lng: 34.57202827508546 },
{ lat: 36.778754712956506, lng: 34.56898128564454 },
{ lat: 36.777414146732426, lng: 34.57179224069215 }
];
coordinate = { lat: 36.779098444109145, lng: 34.57202827508546 };
removeCoordinate(coordinate: Coordinate): Coordinate {
const found = this.coordinates.find((coordinate) => coordinate == coordinate);
if (found) {
this.coordinates.splice(found, 1);
}
return coordinate;
}
There seems to be an error in your array syntax so assuming you mean an array as opposed to an object, Array.splice is your friend here:
someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];
someArray.splice(1,1)
Use javascript's splice() function.
This may help: http://www.w3schools.com/jsref/jsref_splice.asp
You could also use some:
someArray = [{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"}];
someArray.some(item => {
if(item.name === "Kristian") // Case sensitive, will only remove first instance
someArray.splice(someArray.indexOf(item),1)
})
This is what I use.
Array.prototype.delete = function(pos){
this[pos] = undefined;
var len = this.length - 1;
for(var a = pos;a < this.length - 1;a++){
this[a] = this[a+1];
}
this.pop();
}
Then it is as simple as saying
var myArray = [1,2,3,4,5,6,7,8,9];
myArray.delete(3);
Replace any number in place of three. After the expected output should be:
console.log(myArray); //Expected output 1,2,3,5,6,7,8,9
splice(i, 1) where i is the incremental index of the array will remove the object.
But remember splice will also reset the array length so watch out for 'undefined'. Using your example, if you remove 'Kristian', then in the next execution within the loop, i will be 2 but someArray will be a length of 1, therefore if you try to remove "John" you will get an "undefined" error. One solution to this albeit not elegant is to have separate counter to keep track of index of the element to be removed.
Returns only objects from the array whose property name is not "Kristian"
var noKristianArray = $.grep(someArray, function (el) { return el.name!= "Kristian"; });
Demo:
var someArray = [
{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"},
{name:"Kristian", lines:"2,58,160"},
{name:"Felix", lines:"1,19,26,96"}
];
var noKristianArray = $.grep(someArray, function (el) { return el.name!= "Kristian"; });
console.log(noKristianArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This Concepts using Kendo Grid
var grid = $("#addNewAllergies").data("kendoGrid");
var selectedItem = SelectedCheckBoxList;
for (var i = 0; i < selectedItem.length; i++) {
if(selectedItem[i].boolKendoValue==true)
{
selectedItem.length= 0;
}
}