简体   繁体   English

Javascript 基于另一个数组对对象数组进行排序

[英]Javascript sort array of objects based on another array

I have an array of objects I need to sort based on another array objects.我有一个对象数组,我需要根据另一个数组对象进行排序。 This is the given array that needs to be sorted:这是需要排序的给定数组:

const arr1 = [
    {
      id: 21,
      name: 'Joey',
      vehicle: 'car'
    },
    {
      id: 6,
      name: 'Kevin'
      vehicle: 'car'
    },
    {
      id: 10,
      name: 'Luis'
      vehicle: 'van'
    }
  ]

And this is the array that is in the proper order:这是按正确顺序排列的数组:

 const arr2 = [
    {
      id: 6,
      name: 'Kevin'
    },
    {
      id: 21,
      name: 'Joey'
    },
    {
      id: 10,
      name: 'Luis'
    }
  ]

There is no specific order to arr2 its just the data that comes back from my db. arr2没有特定的顺序,它只是从我的数据库返回的数据。 I basically just need to put the ids in arr1 in the same order as thet are in arr2.我基本上只需要按照与 arr2 中相同的顺序将 id 放入 arr1 中。 Ive tried using findIndex and sort but I am very confused我试过使用 findIndex 和排序,但我很困惑

that?那?

 const arr1 = [ { id: 21, name: 'Joey', vehicle: 'car' }, { id: 6, name: 'Kevin', vehicle: 'car' }, { id: 10, name: 'Luis', vehicle: 'van' } ] const arr2 = [ { id: 6, name: 'Kevin' }, { id: 21, name: 'Joey' }, { id: 10, name: 'Luis' } ] // Arr1 ordered.. const arr1_ord = arr2.map(a2=> arr1.find(x=>x.id===a2.id)) console.log( arr1_ord )
 .as-console-wrapper {max-height: 100%;important:top:0}

Also, if there are only 2 items in arr2 I still want those elements that are missing to be at the end of the sorted arr1.此外,如果 arr2 中只有 2 个项目,我仍然希望那些缺失的元素位于排序后的 arr1 末尾。 Would this solve that?这能解决吗?

I add add another case: arr2 element doesn't have a arr1 same id我添加另一种情况:arr2 元素没有 arr1 相同的 id

 const arr1 = [ { id: 21, name: 'Joey', vehicle: 'car' }, { id: 6, name: 'Kevin', vehicle: 'car' }, { id: 12, name: 'George', vehicle: 'carriage' } // not in arr2, { id: 10, name: 'Luis', vehicle: 'van' } ] const arr2 = [ { id: 6, name: 'Kevin' }, { id: 21, name: 'Joey' }, { id: 88, name: 'none' } // not in arr1, { id: 10, name: 'Luis' } ] // Arr1 ordered.. const arr1_ord = arr2.reduce((res, {id},i,{[i+1]:next})=> { let a1 = arr1.find(x=>x.id===id) if (a1) res.push(a1) // if exist in arr1 if (next) return res else return [...res, arr1.filter(r=>.res.some(z=>z.id===r,id))] // add the missing elements }.[]) console.log( arr1_ord )
 .as-console-wrapper {max-height: 100%;important:top:0}

Array.prototype.sort can take in a custom comparison function to sort however you'd like it to. Array.prototype.sort可以接受自定义比较 function 来排序,但是你喜欢它。 The function takes in two arguments (firstValue, secondValue) If that function returns a positive value, then secondValue goes before the firstValue , if it's 0 or negative, then firstValue is sorted before secondValue . function 接受两个 arguments (firstValue, secondValue)如果 function 返回正值,则secondValue排在firstValue firstValue或负值secondValue First/second value are from the array you are sorting.第一个/第二个值来自您正在排序的数组。 In your case, you are sorting based on a different array, but that is fine since you can do that in your function.在您的情况下,您正在根据不同的数组进行排序,但这很好,因为您可以在 function 中执行此操作。

You can do:你可以做:

arr1.sort((firstValue, secondValue) => {
   return findIdInArr2(firstValue.id) - findIdInArr2(secondValue.id);
});

Where you would have to define findIdInArr2 to find the index in arr2, and you can use Array.prototype.findIndex to solve that problem.您必须在哪里定义findIdInArr2才能找到 arr2 中的索引,您可以使用Array.prototype.findIndex来解决该问题。 Where findIndex similarly takes in a function to find the index of something in an array. findIndex同样采用 function 来查找数组中某物的索引。

function findIdInArr2(id) {

    const foundIndex = arr2.findIndex(function(obj) {
        return obj.id === id;
    });
    // If not found, this will be -1.  But that would sort all
    // unfound objects at the beginning of the array.
    // To place these objects at the end of the array, it needs to
    // return a number higher than the rest.  So return infinity.

    return (foundIndex === -1) ? Infinity : foundIndex;

}

note: findIndex is not available in IE, so you'd need to add a polyfill if you are planning on supporting IE.注意: findIndex在 IE 中不可用,因此如果您计划支持 IE,则需要添加 polyfill。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM