我对数组不好,从来没有。所以这可能是一个简单而愚蠢的问题,但这里有:
我有一个对象数组。每个对象如下所示:
obj = {
color: "blue",
name: "Some description",
id: 1
}
目前按以下方式安排:
[Blue, Blue, Beige, Beige, Cyan, Cyan]
我需要做的是根据对象的color
属性对此数组进行排序,如下所示:
[Blue, Beige, Cyan, Blue, Beige, Cyan]
谢谢:)
答案 0 :(得分:1)
对不起,首先我误解了这个问题。
这是我更新的解决方案:
'use strict';
let _ = require('lodash');
let colors = [
{color: "Blue", id: 1},
{color: "Blue", id: 2},
{color: "Beige", id: 3},
{color: "Beige", id: 4},
{color: "Cyan", id: 5},
{color: "Cyan", id: 6},
];
let sort = function(array) {
let order = ["Blue", "Beige", "Cyan"];
let ordered = [];
let nextColor = 0;
do {
let itemIndex = _.findIndex(array, function(item) {
return item.color == order[nextColor];
});
let item = _.pullAt(array, itemIndex);
ordered.push(item.pop());
nextColor++;
if(nextColor == array.length) {
nextColor = 0;
}
} while ( array.length )
return ordered;
}
colors = sort(colors);
console.log(colors);
/*
Result:
[ { color: 'Blue', id: 1 },
{ color: 'Beige', id: 3 },
{ color: 'Cyan', id: 5 },
{ color: 'Blue', id: 2 },
{ color: 'Beige', id: 4 },
{ color: 'Cyan', id: 6 } ]
*/