是否有可能对一个数组进行排序和重排,看起来像这样:
itemsArray = [
['Anne', 'a'],
['Bob', 'b'],
['Henry', 'b'],
['Andrew', 'd'],
['Jason', 'c'],
['Thomas', 'b']
]
要匹配此数组的排列:
sortingArr = [ 'b', 'c', 'b', 'b', 'a', 'd' ]
不幸的是,我没有任何身份证件可以追踪。我需要优先考虑items-array以尽可能接近地匹配sortingArr。
更新:
以下是我正在寻找的输出:
itemsArray = [
['Bob', 'b'],
['Jason', 'c'],
['Henry', 'b'],
['Thomas', 'b']
['Anne', 'a'],
['Andrew', 'd'],
]
知道该怎么做吗?
喜欢的东西:
items = [
['Anne', 'a'],
['Bob', 'b'],
['Henry', 'b'],
['Andrew', 'd'],
['Jason', 'c'],
['Thomas', 'b']
]
sorting = [ 'b', 'c', 'b', 'b', 'c', 'd' ];
result = []
sorting.forEach(function(key) {
var found = false;
items = items.filter(function(item) {
if(!found && item[1] == key) {
result.push(item);
found = true;
return false;
} else
return true;
})
})
result.forEach(function(item) {
document.writeln(item[0]) /// Bob Jason Henry Thomas Andrew
})
下面是一个较短的代码,但它破坏了排序数组:
result = items.map(function(item) {
var n = sorting.indexOf(item[1]);
sorting[n] = '';
return [n, item]
}).sort().map(function(j) { return j[1] })
我希望我能帮助到一些人,但是如果你试图通过第一个数组的键上的另一个数组对一个对象数组进行排序,例如,你想对这个对象数组进行排序:
const foo = [
{name: 'currency-question', key: 'value'},
{name: 'phone-question', key: 'value'},
{name: 'date-question', key: 'value'},
{name: 'text-question', key: 'value'}
];
通过这个数组:
const bar = ['text-question', 'phone-question', 'currency-question', 'date-question'];
你可以这样做:
foo.sort((a, b) => bar.indexOf(a.name) - bar.indexOf(b.name));