如何使用另一个数组对对象数组进行排序以供参考?

时间:2021-01-04 17:43:45

标签: javascript

我想使用另一个只有 id 的数组对具有 id 每个对象的对象数组进行排序,例如:

object = [
 {id: 2, name: carlos},
 {id: 1, name: maria},
 {id: 4, name: juan},
 {id: 3, name: pepe},    //this is the array that i want to be sorted or create a copy to return it
]

    [1,2,3,4,5] //this is the array that i will use as reference to sort the first one

最终结果应该是:

object = [
 {id: 1, name: maria},
 {id: 2, name: carlos},
 {id: 3, name: pepe},
 {id: 4, name: juam},    //this is the array that i want to be sorted or create a copy to return it
]

我使用了两个地图,但我总是使用 undefined 获取和数组:

array_to_be_sorted.map((objects) => {
  array_reference.map((id) => {
     if (objects.id === id) {
        return {...objects}
     }
  }    
}

我使用 map 因为我认为是 bigs 数组的最佳方式,因为我正在构建一个音乐播放器,所以不知道用户有多少曲目

3 个答案:

答案 0 :(得分:2)

您可以使用 Array.prototype.sort() 方法获取结果。

const data = [
  { id: 2, name: 'carlos' },
  { id: 1, name: 'maria' },
  { id: 4, name: 'juan' },
  { id: 3, name: 'pepe' },
];

const order = [1, 2, 3, 4, 5];
data.sort((x, y) => order.indexOf(x.id) - order.indexOf(y.id));
console.log(data);

另一种使用 Map Object 的解决方案比第一个更快。

const data = [
  { id: 2, name: 'carlos' },
  { id: 1, name: 'maria' },
  { id: 4, name: 'juan' },
  { id: 3, name: 'pepe' },
];

const order = [1, 2, 3, 4, 5];
const map = new Map();
order.forEach((x, i) => map.set(x, i));
data.sort((x, y) => map.get(x.id) - map.get(y.id));
console.log(data);

答案 1 :(得分:0)

为什么不直接使用 Array.prototpye.sort()?简单快捷。

const pre = document.querySelector('pre');

let object = [
  {id: 2, name: 'carlos'},
  {id: 1, name: 'maria'},
  {id: 4, name: 'juan'},
  {id: 3, name: 'pepe'}
];

const criteria = [1,2,3,4,5];

pre.innerText = 'object:' + JSON.stringify(object, null, 2) + '\n\n';

object.sort((a, b) => {
  return criteria[a.id] - criteria[b.id];
});

pre.innerText += 'sorted object:' + JSON.stringify(object, null, 2);
Sort an array using criteria from a second array:

<pre></pre>

答案 2 :(得分:0)

您可以利用 Schwartzian transform 并根据另一个数组对数据进行排序。

const data = [ { id: 2, name: 'carlos' }, { id: 1, name: 'maria' }, { id: 4, name: 'juan' }, { id: 3, name: 'pepe' }, ],
      order = [4, 2, 3, 1, 5],
      result = data.map(o => {
                const index = order.indexOf(o.id);
                return [index, o];
              })
              .sort((a, b) => a[0] - b[0])
              .map(([, o]) => o);
console.log(result);