我正在尝试根据所选ID排列数组
例如,我有一个[{id:1}, {id:2}, {id:3}, {id:4}, {id:5}]
数组
所选数组为[3,5];输出将为[{id:1}, {id:3}, {id:5}, {id:2}, {id:4}]
我设法在[3,5]
上进行了正确的排列,但是当我添加/更改所选数组的值时,问题并不一致
var aData = [{id:1},{id:2},{id:3},{id:4},{id:5}];
var selectedId = [3,5];
let firstArray;
selectedId.forEach(function(id) {
let iIndex = selectedId.indexOf(id);
if (iIndex === 0) {
firstArray = iIndex;
}
array_move(aData, id-1, selectedId[firstArray]-2);
});
function array_move(arr, old_index, new_index) {
if (new_index >= arr.length) {
var k = new_index - arr.length + 1;
while (k--) {
arr.push(undefined);
}
}
arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
};
答案 0 :(得分:1)
这会做到的。
$string = 'false';
if( $string == 'true'){
$string = true;
}else if($string == 'false'){
$string= false;
}
如果要保持selectedId数组的顺序,可以首先对selectedId数组应用reduce,以从aData中获取所选项。
然后将结果与selectedId中不存在的aData元素合并。
let output =aData.filter(obj => selectedId.indexOf(obj.id) > -1).concat(aData.filter(obj => selectedId.indexOf(obj.id) ==-1))
console.log(output)
答案 1 :(得分:1)
filter
,然后是concat
:
var aData = [{id:1},{id:2},{id:3},{id:4},{id:5}];
var selectedId = [3,5];
aData = aData.filter(({ id }) => selectedId.includes(id)).concat(aData.filter(({ id }) => !selectedId.includes(id)));
console.log(aData);