Emitsu
Emitsu

Reputation: 31

Creating a new Array from Normal Array and Array of objects

I have two arrays, arr1 is an array of objects and arr2 is just a regular array. I am trying to match arr2 values with the "original" value from the objects of arr1 and return the "new" value into a new resulting array. There's usually more than 2 items in arr2 and the order isn't the always same that's why I couldn't just match by the index each time.

let arr1 = [
        { original: "1x Adjustments", new: "ONETIME_AMT" },
        { original: "Churn", new: "CHURN_AMT" },
        { original: "Funnel", new: "FUNNEL_AMT" },
      ];

let arr2 = [ '1x Adjustments', 'Churn' ]

desiredResult = ["ONETIME_AMT", "CHURN_AMT"]

I tried to use the map function multiple times, but the closest I got was only returning the first element that just happened to match, maybe I need to use a for loop in it too?

var desiredResult = arr2.map(item => item === arr1[0].original ? arr1[0].new : '')

Ideally I thought the [0] could be replaced with i (index), in a for loop but not sure how to implement a for loop in a map function (or if that's even the right solution)

Upvotes: 1

Views: 42

Answers (2)

user3133
user3133

Reputation: 612

You could also use reduce for this purpose!

let arr1 = [
        { original: "1x Adjustments", new: "ONETIME_AMT" },
        { original: "Churn", new: "CHURN_AMT" },
        { original: "Funnel", new: "FUNNEL_AMT" },
      ];

let arr2 = [ '1x Adjustments', 'Churn' ]

const findNew = (arr1, arr2) =>
  arr1.reduce((acc, curr) => {
    if(arr2.includes(curr.original)) {
      acc.push(curr.new)
    }
    return acc
  }, [])

console.log(findNew(arr1, arr2))

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191976

Convert arr1 to a Map (arr1Map), and then map arr2, and get the new value from arr1Map:

const arr1 = [{"original":"1x Adjustments","new":"ONETIME_AMT"},{"original":"Churn","new":"CHURN_AMT"},{"original":"Funnel","new":"FUNNEL_AMT"}]
const arr2 = [ '1x Adjustments', 'Churn' ]

const arr1Map = new Map(arr1.map(o => [o.original, o.new]))
const result = arr2.map(key => arr1Map.get(key))

console.log(result)

Upvotes: 1

Related Questions