Home > database >  Find values in array of object with another array of strings
Find values in array of object with another array of strings

Time:08-26

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'];

CodePudding user response:

You want to return something for each value in arrVar, so you probably want 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

CodePudding user response:

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)

CodePudding user response:

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)

  • Related