Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map an ID array to a string array using via an object list

var myIds = [3, 4, 2];

var myObj = [
    {id:1, name:'one'}, 
    {id:2, name:'two'},
    {id:3, name:'tree'},
    {id:4, name:'four'}];

// need to obtain ['tree', 'four', 'two']

var idsToNames= function(ids, objects) {
    var myNames = myIds.map(function(id){
        // transform id to name
        foreach(o in objects){
            if (i.id == id) 
                return o.name;
        }
    });
    return myNames;
}

Is it the optimal way to transform a id array into a name array?

like image 937
serge Avatar asked Nov 21 '25 08:11

serge


1 Answers

First transform your object like this

var newMyObj = myObj.reduce(function(result, currentObject) {
  result[currentObject.id] = currentObject.name;
  return result;
}, {});

console.log(newMyObj);
// { '1': 'one', '2': 'two', '3': 'three', '4': 'four' }

You can actually create the newMyObj by iterating the array myObj, like this as well

var newMyObj = {};
for (var i = 0; i < myObj.length; i += 1) {
  newMyObj[myObj[i].id] = myObj[i].name;
}

Now, you can simply iterate myIds and pick values from newMyObj, like this

console.log(myIds.map(function(id) { return newMyObj[id]; }));
// [ 'three', 'four', 'two' ]

If your environment supports ECMAScript 2015's Arrow functions, this can be written succinctly as

console.log(myIds.map((id) => newMyObj[id]));
// [ 'three', 'four', 'two' ]

By transforming your original myObj to newMyObj you will be getting constant time lookup. Otherwise you have to iterate the myObj array for every element in the myIds and runtime complexity will become O(n*m).

like image 142
thefourtheye Avatar answered Nov 23 '25 21:11

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!