Remove elements from an array except one

I have two arrays. The first is an array of indices and the second 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]

. The result will look like this:

obj = [Object_2]

      

There are also cases when nums = [0, 1, 2]

and obj = [Object_1, Object_2, Object_3]

; In this case, I don't need to delete any items.

The length " obj

" is always greater than the length "nums".

So, I started by finding only the items that I need to keep:

nums.forEach(function(key) {
    obj.forEach(function(o, o_key) {
        if (key === o_key) {
            console.log(key, o);
            // deleting remaining elements
        }
    });
});

      

Question: how can I delete items that do not match my state? I don't need a new array, I want to modify the existing "obj" array. How can I achieve this functionality? Or should I use some other methods?

+3


source to share


3 answers


You check if the length of the indices is the same length of the array of objects and returns or removes objects at the given indices.

The indices require a sorted array because it Array#splice

changes the length of the array. (With an array with descending sorted indices, you can use Array#forEach

instead 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; }
      

Run codeHide result


+3


source


You can do this with a filter, assuming that nums

is an array by the indices of the items you want to store.



obj = obj.filter((o, i) => nums.indexOf(i) > -1); 

      

+1


source


If you want to keep the same array object you need to use splice

eg. to a simple reverse for

so as not to mess up the indexes:

for (var i=obj.length-1; i>=0; i--) {
    if (nums.indexOf(i) < 0) {
        obj.splice(i, 1);
    }
}

      

This assumes that the list of indices (nums) is ordered. If not, we first have to sort it:

var sortedNums = nums.sort(function (a, b) {  return a - b;  });

      

And then use sortedNums to check indexOf

+1


source







All Articles