-3

I have two javascript array, One is Object array and another is string array.

Sample Arrays

const arr1 = [{"key": "Jon", "value" : "King"},
              {"key": "Danny", "value" : "Queen"},
              {"key": "Cersei", "value" : "False Queen"},
              {"key": "Tyrion", "value" : "Hand"}]

const arr2 = ["Jon","Tyrion"]

I want to console log or print on html output like below. I dont want comma after hand. Required Output

King, Hand

Please suggest how can it be done using map or filter. Oneliners are very much appreciated.

2 Answers2

2

If you just want to filter by key and disply the related value,then below code snippet is a reference for you

const arr1 = [{"key": "Jon", "value" : "King"},
              {"key": "Danny", "value" : "Queen"},
              {"key": "Cersei", "value" : "False Queen"},
              {"key": "Tyrion", "value" : "Hand"}]

const arr2 = ["Jon","Tyrion"]

let result = arr1.filter(a => arr2.some(b => b == a.key )).map(a => a.value).join(", ")

console.log(result)
flyingfox
  • 13,414
  • 3
  • 24
  • 39
0

At this point you can use the filter function from the prototype array.

const filtered = arr1.filter(elem => elem.key=== 'Jon' || elem.key=== 'Tyrion')

Alternatively, you can also run more complex checks

const filtered = arr1.filter(elem => {
    return elem.key=== 'Jon' || elem.key=== 'Tyrion'
})

More about this is well described at mozilla developer.mozilla.org

Update after the question was edited

const filtered = arr1.filter(elem => elem.key=== 'Jon' || elem.key=== 'Tyrion')

console.log(filtered.map(elem => elem.value).join(', '))
Maximilian Fixl
  • 670
  • 6
  • 23
  • `[object Object], [object Object]` is not the output the OP is looking for. You're also hardcoding the names now instead of looking at `arr2`. – Cerbrus Oct 19 '22 at 09:56
  • @Cerbrus absolutely correct. The map function must have slipped through. Answer edited. – Maximilian Fixl Oct 19 '22 at 10:41