0

I am trying to work out how I can return a list with values from the own key in the array bellow if the object name value matches values in the lookupvalues array

lookupvalues = ["ross","linda"]
resources = [{own: "car", name: "bob"},{own: "bike", name: "ross"},{own: "plane", name: "linda"}]
wanted_output = ["bike","plane"]

I am struggling a bit with a good method to use for when I need to compare value in an object with array values. Is there a reasonable straight forward way to do this?

I must say how impressed I am that I got 4 replies with working examples at the same time!

4 Answers 4

1

One way (array method chaining) is that you could filter by name and map to grap each's own

const lookupvalues = ["ross", "linda"]
const resources = [
  { own: "car", name: "bob" },
  { own: "bike", name: "ross" },
  { own: "plane", name: "linda" },
]

const res = resources
  .filter(({ name }) => lookupvalues.includes(name))
  .map(({ own }) => own)

console.log(res)

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

Comments

1
resources.filter(resource => lookupvalues.includes(resource.name))
  .map(resource => resource.own);

This will filter by the items that have names that are included in lookupvalues, and then transform the array into an array of the own values of those remaining.

Comments

1

You can take the help of Array#filter and Array#map:

const lookupvalues = ["ross","linda"]
const resources = [{own: "car", name: "bob"},{own: "bike", name: "ross"},{own: "plane", name: "linda"}]

const filterRes = (arr) => {
  const lookup = new Set(lookupvalues);
  return arr.filter(({name}) => lookup.has(name))
            .map(({own}) => own);
}
console.log(filterRes(resources));

3 Comments

Did you use a Set just for the optimization between includes and has?
@CoryHarper yes, here it won't make much difference but for a lengthy lookupvalues array it would.
Same reason I was thinking to perhaps suggest making lookup values just an object of string => true pairs, when it's initialized.
1
resources.filter(item => lookupvalues.indexOf(item.name) > -1).map(item => item.own)

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.