2016-03-01 185 views
1

我想使用一個字符串數組作爲模板如何排序其他數組。使用數組作爲排序順序

var sort = ["this","is","my","custom","order"]; 

,然後我要作爲排序依據由命令鍵(內容)對象的數組:

var myObjects = [ 
    {"id":1,"content":"is"}, 
    {"id":2,"content":"my"}, 
    {"id":3,"content":"this"}, 
    {"id":4,"content":"custom"}, 
    {"id":5,"content":"order"} 
]; 

,使我的結果是:

sortedObject = [ 
    {"id":3,"content":"this"},   
    {"id":1,"content":"is"}, 
    {"id":2,"content":"my"}, 
    {"id":4,"content":"custom"}, 
    {"id":5,"content":"order"}  
]; 

怎麼會我那樣做?

回答

3

你可以做這樣的事情與sort()indexOf()

var sort = ["this", "is", "my", "custom", "order"]; 
 

 
var myObjects = [{ 
 
    "id": 1, 
 
    "content": "is" 
 
}, { 
 
    "id": 2, 
 
    "content": "my" 
 
}, { 
 
    "id": 3, 
 
    "content": "this" 
 
}, { 
 
    "id": 4, 
 
    "content": "custom" 
 
}, { 
 
    "id": 5, 
 
    "content": "order" 
 
}]; 
 

 
var sortedObj = myObjects.sort(function(a, b) { 
 
    return sort.indexOf(a.content) - sort.indexOf(b.content); 
 
}); 
 

 
document.write('<pre>' + JSON.stringify(sortedObj, null, 3) + '</pre>');

0

你需要使用.map

var sort = ["this", "is", "my", "custom", "order"]; 
 
var myObjects = [{ 
 
    "id": 1, 
 
    "content": "is" 
 
}, { 
 
    "id": 2, 
 
    "content": "my" 
 
}, { 
 
    "id": 3, 
 
    "content": "this" 
 
}, { 
 
    "id": 4, 
 
    "content": "custom" 
 
}, { 
 
    "id": 5, 
 
    "content": "order" 
 
}]; 
 
var myObjectsSort = sort.map(function(e, i) { 
 
    for (var i = 0; i < myObjects.length; ++i) { 
 
     if (myObjects[i].content == e) 
 
     return myObjects[i]; 
 
    } 
 
}); 
 
document.write('<pre>' + JSON.stringify(myObjectsSort , null, 3) + '</pre>');
幫助

0

創建一個新的陣列和每個對象廣場myObjects考慮的sort

index試試這個:

var sort = ["this", "is", "my", "custom", "order"]; 
 
var myObjects = [{ 
 
    "id": 1, 
 
    "content": "is" 
 
}, { 
 
    "id": 2, 
 
    "content": "my" 
 
}, { 
 
    "id": 3, 
 
    "content": "this" 
 
}, { 
 
    "id": 4, 
 
    "content": "custom" 
 
}, { 
 
    "id": 5, 
 
    "content": "order" 
 
}]; 
 
var newArr = []; 
 
myObjects.forEach(function(item) { 
 
    var index = sort.indexOf(item.content); 
 
    newArr[index] = item; 
 
}); 
 
console.log(newArr);
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

0

I S uggest使用一個對象來存儲排序順序。

var sort = ["this", "is", "my", "custom", "order"], 
 
    sortObj = {}, 
 
    myObjects = [{ "id": 1, "content": "is" }, { "id": 2, "content": "my" }, { "id": 3, "content": "this" }, { "id": 4, "content": "custom" }, { "id": 5, "content": "order" }]; 
 

 
sort.forEach(function (a, i) { sortObj[a] = i; }); 
 

 
myObjects.sort(function (a, b) { 
 
    return sortObj[ a.content] - sortObj[ b.content]; 
 
}); 
 
\t 
 
document.write('<pre>' + JSON.stringify(myObjects, 0, 4) + '</pre>');