是否有可能对一个数组进行排序和重排,看起来像这样:

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'],
]

知道该怎么做吗?


当前回答

如果你在这里需要用一个对象数组来做这件事,这里是@Durgpal Singh的精彩答案的改编:

const itemsArray = [
  { name: 'Anne', id: 'a' },
  { name: 'Bob', id: 'b' },
  { name: 'Henry', id: 'b' },
  { name: 'Andrew', id: 'd' },
  { name: 'Jason', id: 'c' },
  { name: 'Thomas', id: 'b' }
]

const sortingArr = [ 'b', 'c', 'b', 'b', 'a', 'd' ]

Object.keys(itemsArray).sort((a, b) => {
  return sortingArr.indexOf(itemsArray[a].id) - sortingArr.indexOf(itemsArray[b].id);
})

其他回答

为了获得一个新的有序数组,您可以使用Map并收集数组中所有具有所需键的项,并通过获取所需组的筛选元素来映射所需的有序键。

var itemsArray =[[“安妮”,' '],[“鲍勃”、“b”],[“亨利”、“b”],[“安德鲁”,' d '],[“杰森”、“c”],[“托马斯”、“b”]], sortingArr = ['b', 'c', 'b', 'b', 'a', 'd'], map = itemsArray。减少((m) = > m.set ([1], (m.get ([1 ]) || []). concat ([a])),新地图), result = sortingArr。Map (k => (Map .get(k) || []).shift()); console.log(结果);

使用jQuery的$. inarray()方法。然后你可以这样做

var sortingArr = [ 'b', 'c', 'b', 'b', 'c', 'd' ];
var newSortedArray = new Array();

for(var i=sortingArr.length; i--;) {
 var foundIn = $.inArray(sortingArr[i], itemsArray);
 newSortedArray.push(itemsArray[foundIn]);
}
  const result = sortingArr.map((i) => {
    const pos = itemsArray.findIndex(j => j[1] === i);
    const item = itemsArray[pos];
    itemsArray.splice(pos, 1);
    return item;
  });

用数值排序:

itemsArray.sort(function(a, b){  
  return sortingArr[itemsArray.indexOf(a)] - sortingArr[itemsArray.indexOf(b)];
});
let sortedOrder = [ 'b', 'c', 'b', 'b' ]
let itemsArray = [ 
    ['Anne', 'a'],
    ['Bob', 'b'],
    ['Henry', 'b'],
    ['Andrew', 'd'],
    ['Jason', 'c'],
    ['Thomas', 'b']
]
a.itemsArray(function (a, b) {
    let A = a[1]
    let B = b[1]

    if(A != undefined)
        A = A.toLowerCase()

    if(B != undefined)
        B = B.toLowerCase()

    let indA = sortedOrder.indexOf(A)
    let indB = sortedOrder.indexOf(B)

    if (indA == -1 )
        indA = sortedOrder.length-1
    if( indB == -1)
        indB = sortedOrder.length-1

    if (indA < indB ) {
        return -1;
    } else if (indA > indB) {
        return 1;
    }
    return 0;
})

如果排序键在引用数组中不存在,此解决方案将在末尾附加对象