简体   繁体   中英

How to get index of removed element in the sub array

I have an array all = [2,3,4,12, 55,33] and ar1 = [12, 55, 33] which is a sub array of all (starts from 12).

When I remove a value from all which is a part of ar1 (ex:12) how do I get the index of that value in ar1 (for 12 it is 0) so that I can remove it from ar1 also.

Edit: I actually have objects in my array. I used numbers here as example

Since you specified that your array contains objects, you should give each object an individual id , so that you can use the id to filter it. Your objects, apart from the id , can hold any other data.

You can then use Array.findIndex to find the index of the corresponding object.

Example:

const arr = [{ id: "abc" }, { id: "def" }];
arr.findIndex (itm => itm.id === "def") // Returns 1

Alternatively, in case you cannot add an id , you will have do do a deep object comparison (which is not 100% accurate, but works in most cases). You could either use a standalone implementation, or, for example, Lodash's _.isEqual .

Actually, you can use Array#splice() to remove the element from the first array, then check for its index using Array#findIndex() and then remove it from the second array .

var [removed] = all.splice(3, 1);
var index = ar1.findIndex(el => el.val == removed.val);
if (index !== -1) {
  ar1.splice(index, 1);
}

Demo:

 var all = [{ val: 2}, { val: 3}, {val: 4}, {val: 12}, {val: 55 }, {val: 33}], ar1 = [{val: 12}, {val: 55}, {val: 33}]; var [removed] = all.splice(3, 1); console.log(removed); var index = ar1.findIndex(el => el.val == removed.val); if (index !== -1) { ar1.splice(index, 1); } console.log(ar1); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM