How to match one object array and string array in javascript and produce custom result seperated by commas?

465 Views Asked by At

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

There are 2 best solutions below

2
Maximilian Fixl On BEST ANSWER

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(', '))
0
flyingfox On

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)