I have two arrays. First one is an array of indexes and second one is an array of objects. They look like this:
var nums = [0, 2];
var obj = [Object_1, Object_2, Object_3];
In this particular case I need to remove all "obj
" elements except obj[0]
and obj[2]
. So the result will look like this:
obj = [Object_2]
There are also may be cases when nums = [0, 1, 2]
and obj = [Object_1, Object_2, Object_3]
; In that case I dont need to remove any elements.
The "obj
" length is always greater than "nums" length.
So I started with finding only the elements that I need to save:
nums.forEach(function(key) {
obj.forEach(function(o, o_key) {
if (key === o_key) {
console.log(key, o);
// deleting remaining elements
}
});
});
The question: How can I remove elements that dont meets my condition? I dont need the new array, I want to modify the existing "obj" array. How can I achieve this functionality? Or should I use some another techniques?
You coudld check if the length of the indices is the same length of the object array and return or delete the objects at the given indices.
It needs a sorted array for indices, because Array#splice
changes the length of the array. (With an array with descending sorted indices, you could use Array#forEach
instead of Array#reduceRight
.)
function mutate(objects, indices) {
if (objects.length === indices.length) {
return;
}
indices.reduceRight(function (_, i) {
objects.splice(i, 1);
}, null);
}
var objects = [{ o: 1 }, { o: 2 }, { o: 3 }];
mutate(objects, [0, 1, 2]); // keep all items
console.log(objects);
objects = [{ o: 1 }, { o: 2 }, { o: 3 }]; // delete items at index 0 and 2
mutate(objects, [0, 2]);
console.log(objects);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With