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?
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?
Share Improve this question edited Nov 27, 2015 at 16:31 thefourtheye 240k53 gold badges465 silver badges500 bronze badges asked Nov 27, 2015 at 16:23 sergeserge 15.2k41 gold badges142 silver badges234 bronze badges1 Answer
Reset to default 7First 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 plexity will bee O(n*m).