1

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)

2
  • 1
    can you add the result in literal notation? Commented Apr 11, 2020 at 17:11
  • I think my problem is how i handle the result. Thanks Nina and mplungjan Commented Apr 11, 2020 at 17:19

2 Answers 2

2

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

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

Comments

2

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)

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.