简体   繁体   中英

Getting the indexes of elements in one array based on the other

In javascript I have an array that looks like this:

arrFull = [[14, "Hello"], [20, "Hello2"], [40, "Hello3"], [62, "Hello4"], [100, "Hello5"]]

Out of these I add some elements in a new array like:

arrChosen = [[20, "Hello2"], [100, "Hello5"]]

How can I make a new array that contains the indices of the choosed elements based on the original array:

like indices = [1, 4]

You need to check the values of the arrays and get the indices.

 var array = [[14, "Hello"], [20, "Hello2"], [40, "Hello3"], [62, "Hello4"], [100, "Hello5"]], chosen = [[20, "Hello2"], [100, "Hello5"]], indices = chosen.map(a => array.findIndex(b => a.length === b.length && a.every((v, i) => v === b[i])) ); console.log(indices);

 var arrFull = [ [14, "Hello"], [20, "Hello2"], [40, "Hello3"], [62, "Hello4"], [100, "Hello5"] ] var arrChosen = [ [20, "Hello2"], [100, "Hello5"] ] function findIndices(chosen, full) { return chosen.map(function(c) { for (var i = 0; i < full.length; i++) { if (full[i][0] === c[0] && full[i][1] === c[1]) return i; } }); } console.log(findIndices(arrChosen, arrFull));

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