Reputation: 6019
Given the array:
myArr = [
{'a':1},
{'b':1},
{'b':2},
{'a':1},
{'b':2}
]
And the index 0
, which has the object {'a':1}
, I would like to get back the array:
[{'b':1},{'b':2},{'b':2}]
keeping the original sort order.
That is removing the object in index 0
and all other objects which are the equivalent.
Is there an elegant way?
Upvotes: 1
Views: 84
Reputation: 161
This works for me
myArr = [
{'a':1},
{'b':1},
{'b':2},
{'a':1},
{'b':2}
]
//Get first item
for(var key in myArr[0]){
var firstItem = key;
}
alert('First item: ' + firstItem);
//Remove matches
var removedItems = []; //Not needed, just used to show you what it's removing.
myArr.forEach(function(item){
for (var key in item){
if(key == firstItem){
removedItems.push(key); //Not needed
myArr.splice(item, 1); //Remove the array entry
}
}
});
alert('Removed items: ' + removedItems);
Upvotes: 0
Reputation: 198314
If you want to remove the same object, it is simple:
a1 = { a: 1 }
b1 = { b: 1 }
b2 = { b: 2 }
myArr = [ a1, b1, b2, a1, b2 ]
var filtered = myArr.filter(o => o != a1)
console.log(filtered);
// [ {b: 1}, {b: 2}, {b: 2} ]
However, if you want to remove an equivalent object, it gets complicated, because by default JavaScript does not have an object equivalence test. You can implement one yourself, or rely on one of the libraries like lodash:
var myArr = [
{'a':1},
{'b':1},
{'b':2},
{'a':1},
{'b':2}
];
var filtered = _.filter(myArr, o => !_.isEqual(o, {a: 1}));
console.log(filtered);
// [ {b: 1}, {b: 2}, {b: 2} ]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.6/lodash.min.js"></script>
Then again, if you're using lodash, you might as well just use it to the full extent:
var myArr = [
{'a':1},
{'b':1},
{'b':2},
{'a':1},
{'b':2}
];
var filtered = _.differenceWith(myArr, [{a: 1}], _.isEqual);
console.log(filtered);
// [ {b: 1}, {b: 2}, {b: 2} ]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.6/lodash.min.js"></script>
which basically does the same thing, but a bit more readably.
Upvotes: 4
Reputation: 19
try myArr.shift();
It will return {'a':1}
And myArr will be [{'b':1},{'b':2},{'b':2}]
Upvotes: -3