0

Requirement - I would like to fetch labels from the array of object if the id exists which will be fetched from another array. If that id don't exists, I would like to return that id from the second array.

var objectVar = [{ id: '1', label: 'One' }, { id: '2', label: 'Two' }, { id: '3', label: 'Three' }];
var arrVar = ['1', '2', '3', '4'];

Here, as 1,2,3 exists I would like to return the labels of it and since 4 doesn't exist in array of object, I would like to return 4. This can be stored in a new Array.

Expected result might look like this -

result = ['One', 'Two', 'Three', '4'];

3 Answers 3

1

You want to return something for each value in arrVar, so you probably want Array#map. The function we'll apply to each item will check if the item exists as an id in objectVar.

We'll use Array#find to search objectVar for the object with a matching id.

We'll use the ternary operator to choose whether to return the found object's label or our arrVar number.

var objectVar = [
  { id: '1', label: 'One' }, 
  { id: '2', label: 'Two' },
  { id: '3', label: 'Three' }
];
var arrVar = ['1', '2', '3', '4'];

const output = arrVar.map(i => {
  let found = objectVar.find(o => o.id === i);
  return found ? found.label : i;
});

console.log(output);


This approach is nearly twice as fast as the other proposed answers in a single run. The mapper function approach might be faster if you have to repeatedly test new arrVar arrays against objectVar.

JSBench.me run showing the runs in the table below

Approach Ops/s Result
Mapper function 3,237,444.05 37.43% slower
Array#map, Array#find 5,174,453.56 Fastest
Array#filter 3,453,123.01 33.27% slower
Sign up to request clarification or add additional context in comments.

Comments

0

let objectVar = [{ id: '1', label: 'One' }, { id: '2', label: 'Two' }, { id: '3', label: 'Three' }];
let arrVar = ['1', '2', '3', '4'];
let output = arrVar.map(a => {
    let matched = objectVar.filter(x => x.id == a);
    if(matched.length > 0) {
        return matched[0].label;
    }
    return a;
});
console.log(output)

Comments

0

You could create a mapper object which maps id to the label

const objectVar = [{ id: '1', label: 'One' }, { id: '2', label: 'Two' }, { id: '3', label: 'Three' }],
      arrVar = ['1', '2', '3', '4'],
      labelMapper = Object.fromEntries(objectVar.map(o => [o.id, o.label])),
      output = arrVar.map(n => labelMapper[n] ?? n)

console.log(output)

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.