Returning the array in an array of arrays with a value from another array

I have and array of arrays aa = [['a'], ['b'], ['c']] and i have an array a = ['a', 'b', 'c'] I need to get the item in aa for each element in a i.e i want to list elements in a with their respective arrays in aa the result should be like a: ['a'] b: ['b'] c: ['c'] I tried this code but it does return the first element i aa for each element in a

I wonder what's wrong here

const aa = [
  ['a'],
  ['b'],
  ['c']
]
const a = ['a', 'b', 'c']

let b = []
a.forEach((el) => {
  b.push(
    aa.filter((element) => {
      return element.includes(el)
    })
  )
})
console.log(b)

Upvotes: 1

Views: 1701

Answers (2)

mplungjan
mplungjan

Reputation: 178421

Try this

const aa = [
  ['a'],
  ['b'],
  ['c']
];
const a = ['a', 'b', 'c'];
let b = {};
a.forEach( // loop "a"
  aEl => b[aEl] = aa.filter(   // filter "aa" 
    aaEl => aaEl.includes(aEl) // on array that includes the item from 'a'
  ).flat() // we need to flatten the resulting array before returning it
);
console.log(JSON.stringify(b)); // using stringify to make it readable

Upvotes: 2

Sijmen
Sijmen

Reputation: 506

Since you want your output to be a key-value list (a: ['a']), variable b should be a map. Let's also rename b to out for readability.

out = {}

To get a better view of if our code is working, let's use some unique test data, and let's rename a to keys and aa to values.

const keys = ['A', 'B', 'C']

const values = [
      ['A', 'A2', 'a3'],
      ['B1', 'B', 'b3'],
      ['C1', 'C2', 'C']
    ]

For every key in keys, we want to set search for all arrays in values that contain the key. To set the search result to out we use brackets like so:

keys.forEach((key) => {
    out[key] = values.filter(valueArr => valueArr.includes(key))
})

This outputs:

{
  "A": [["A", "A2", "a3"]],
  "B": [["B1", "B", "b3"]],
  "C": [["C1", "C2", "C"]]
}

Now there are two arrays around each value. This is because values.filter can return multiple arrays. To combine these into a single array you can use the flat() function. The whole code looks like:

const keys = ['A', 'B', 'C']

const values = [
  ['A', 'A2', 'a3'],
  ['B1', 'B', 'b3'],
  ['C1', 'C2', 'C']
]
out = {}
keys.forEach((key) => {
    out[key] = values.filter(valueArr => valueArr.includes(key)).flat()
})

console.log(out)

Upvotes: 2

Related Questions