0

I have two arrays. I want to find the index of currentArr positions in originalArr. Both the arrays are updated on run time.

let currentArr= [[450, 30, "down"],[480, 60, "right"]]
let originalArr = [[510, 60, "right"],[480, 60, "right"],[450, 60, "down"],[450, 30, "down"], [450, 0, "right"]]

Can anyone pls help me with this?

1
  • 2
    What's wrong with iterating through originalArr and find the entry from currentArr, then remembering the index? Or in other words: please show your current code. Commented Mar 2, 2019 at 12:06

2 Answers 2

2

You can use the function map and the function findIndex to look for the matches.

This alternative checks the length as well as each index value using the function every.

I'm assuming the indexes should be at the same position

let currentArr= [[450, 30, "down"],[480, 60, "right"]]
let originalArr = [[510, 60, "right"],[480, 60, "right"],[450, 60, "down"],[450, 30, "down"], [450, 0, "right"]];

let indexes = currentArr.map(a => originalArr.findIndex(ia => ia.length === a.length && ia.every((e, i) => e === a[i])));

console.log(indexes);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Comments

2

Since the inner arrays will always be in the same order, you could use JSON.stringify to compare the stringified version of arrays:

let currentArr= [[450, 30, "down"],[480, 60, "right"]]
let originalArr = [[510, 60, "right"],[480, 60, "right"],[450, 60, "down"],[450, 30, "down"], [450, 0, "right"]];

let indexes = currentArr.map(c =>  
                originalArr.findIndex(o => JSON.stringify(o) === JSON.stringify(c)));

console.log(indexes);

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.