Search code examples
javascriptarraysarray-maparray-filter

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


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.


Solution

  • 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(', '))