0

If I have an array such as:

let arr = ["So 2545", "Cool 1123", "Mos 1999"] 

that is a subset of a larger array:

let largerArr = ["So 2545", "Fun 1023", "Loss 2009", "Cool 1123", "Mos 1999"]

How can I determine the index of each matching element in the larger array so the output would be another array (i.e. let output = [0,3,4])

2 Answers 2

3

You can use map() with indexOf():

const part = ["So 2545", "Cool 1123", "Mos 1999"];
const full = ["So 2545", "Fun 1023", "Loss 2009", "Cool 1123", "Mos 1999"];

const indexes = part.map(v => full.indexOf(v));

console.log(indexes);

If you are dealing with large arrays, the overhead of building a lookup table (as suggested in other answers) might become worth it.

Sign up to request clarification or add additional context in comments.

Comments

1

You could use .reduceRight() to make a look-up table of indexes, and then you .map() on your arr to map each element to an index from the look-up table:

const arr = ["So 2545", "Cool 1123", "Mos 1999"];
const largerArr = ["So 2545", "Fun 1023", "Loss 2009", "Cool 1123", "Mos 1999"];

const lut = largerArr.reduceRight((m, x, i) => m.set(x, i), new Map);
const output = arr.map(elem => lut.get(elem));
console.log(output);

The purpose of using .reduceRight() is to find the first indexes that the match appears at in the array if the item appears more than once (not the last)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.