2016-03-01 108 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>');