Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove elements from array except particular one

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?

like image 459
Luchnik Avatar asked Dec 19 '22 07:12

Luchnik


1 Answers

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; }
like image 151
Nina Scholz Avatar answered Dec 24 '22 00:12

Nina Scholz