0

I want sort values ​​by array Another

for example

var objName = [{id:1, name:"one"},{id:2, name:"two"}, {id:3, name:"three"}];
var sortById = [1,3,2];

I want this output in that order

1 one
3 three
2 two
1
  • 2
    Can we see your unsuccessful attempts? Commented Jan 24, 2014 at 0:51

4 Answers 4

2

Stuff objName elements into a hash (i.e. object) indexed by id, then map the sortById array onto the hash values.

Exact code left as an exercise for the reader.

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

2 Comments

The ideal answer for the given question in my humble opinion. I wish I could +1 once again
@Nick Manning: you're confusing the teaching process with crowd funding.
0
sorted=new Array()
for(var id_index=0;id_index<sortById.length;id_index++)
{
    for(var obj_index=0;obj_index<objName.length;obj_index++){
        if (objName[obj_index].id===sortById[id_index]) sorted.push(objName[obj_index])
    }
}
//now sorted is the new sorted array. if you want to overwrite the original object:
objName=sorted;

1 Comment

Won't work, he wants to sort by id. Who says the ids are in the correct order in the first array?
0

Supposing that the length of both arrays are the same you can first create a hash:

var objName = [{id:1, name:"one"},{id:2, name:"two"}, {id:3, name:"three"}];
var myHash = {};
for(var i = 0; i<objName.length;i++){
    myHash[objName[i].id] = objName[i];
}

Once you have this hash, you can loop over your keys array and get the values out:

var sortById = [1,3,2];
var sortedArray = [];
for(var i = 0; i<sortById.length;i++){
    sortedArray.push(myHash[sortById[i]]);
}

Comments

0

Something clear and readable (subjective, probably not for everyone):

var result = [];
sortById.forEach(function(id) {
    result = result.concat(objName.filter(function(i) {
        return i.id == id;
    }));
});

JSFiddle: http://jsfiddle.net/RLH6F/

Implemented just for fun.

Warning: O(n^2)

PS: I agree it would be better just give the recipe without the code, but as soon as there are already community members provided the copy-paste solutionы I decided to provide at least a nice looking one.

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.