3
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?

1 Answer 1

7

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).

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

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.