1

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)

1
  • 1
    use Array.find, code: arr2.map(item => arr1.find(({original}) => original == item ).new) Commented Jun 5, 2021 at 0:41

2 Answers 2

1

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)

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

2 Comments

Wow that was very insightful, I didn't know you could create a Map from an array, does that essentially take out the array from it and leave it as an object? The Javascript docs are a bit confusing
The Map's constructor accepts an array (actually any iterable) with a structure of [[key, value], [key, value]]. In this case the temp array would be garbage collected after the Map is created.
1

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))

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.