user3091744
user3091744

Reputation:

How to compare 2 arrays, return the keys from matches from the array to rewrite the keys in first array

I have 2 Arrays:

const firstArray = ["A", "B", "1", "2", "F", "89", "8", "K"];
const inputArray = ["1", "B", "F", "A", "89"];

And with

for (const index of firstArray.keys()) {
  console.log(index);
}

I get the keys from my Array: 0, 1, 2, 3, 4, 5, 6, 7, 8

And with

for (const index of inputArray .keys()) {
  console.log(index);
}

I get the keys from my input array: 0, 1, 2, 3, 4

I use this to compare and check if all elements are in firstArray:

const foundedArray = inputArray.filter(element => firstArray.includes(element));

All fine till here, but now I need to get the keys from firstArray into my inputArray that they fit to the same matching values from firstArray.

I need get the keys from firstArray into my input array:

Value ["1", "B", "F", "A", "89"];
Keys    2,   1,   4,   0,   5

Im stucking here how can I write this.

playground: https://jsfiddle.net/alaber/u792gdfa/

thank you!

Upvotes: 3

Views: 74

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386654

For getting a reordered array, you could count the values of inputArray and filter firstArray by checking the leftover count and decrement the count.

const
    firstArray = ["A", "B", "1", "2", "F", "89", "8", "K"],
    inputArray = ["1", "B", "F", "A", "89"],
    count = inputArray.reduce((count, value) => {
        count[value] = (count[value] || 0) + 1;
        return count;
    }, {}),
    result = firstArray.filter(value => count[value] && count[value]--);

console.log(result);

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138317

  inputArray.map(it => firstArray.indexOf(it))

Using indexOf you can get the position of a certain value innthe array.

Upvotes: 4

Related Questions