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

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

知道该怎么做吗?


当前回答

使用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 sortListByRanking = (rankingList, listToSort) => {
  let result = []

  for (let id of rankingList) {
    for (let item of listToSort) {
      if (item && item[1] === id) {
        result.push(item)
      }
    }
  }

  return result
}

函数sortFunc(a, b) { var sortingArr = ["A", "B", "C"]; 返回sortingArr.indexOf(a.type) - sortingArr.indexOf(b.type); } const itemsArray = [ { 类型:“A”, }, { 类型:“C”, }, { 类型:“B”, }, ]; console.log (itemsArray); itemsArray.sort (sortFunc); console.log (itemsArray);

使用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]);
}

为了获得一个新的有序数组,您可以使用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(结果);

  const result = sortingArr.map((i) => {
    const pos = itemsArray.findIndex(j => j[1] === i);
    const item = itemsArray[pos];
    itemsArray.splice(pos, 1);
    return item;
  });