简体   繁体   English

如何按 javascript 中的属性值对对象的多维数组进行排序?

[英]How to sort a multidimensional array of objects by property value in javascript?

I have the following array:我有以下数组:

const result = [
  [{value: 123, parentID: 1}, {value: 'string123', parentID: 2}],
  [{value: 54764, parentID: 1}, {value: 'string321', parentID: 2}],
  [{value: 321, parentID: 1}, {value: 'string565632', parentID: 2}],
]

and I need to sort this, multidimensional array based on the value, but which object to select is based on parentID .我需要根据值对这个多维数组进行排序,但是 object 到 select 是基于parentID的。

What I have tried so far:到目前为止我已经尝试过:

const parentID = 1;
const sortedResult = result.filter((row) => {
  const selectedColumn = row.find((column) => column.parentID === parentID));
  return _.orderBy(selectedColumn, ['value'], ['asc']);
});

but this isn't working, any ideas what could?但这不起作用,有什么想法可以吗?

Desired output would be:所需的 output 将是:

[
  [{value: 123, parentID: 1}, {value: 'string123', parentID: 2}],
  [{value: 321, parentID: 1}, {value: 'string565632', parentID: 2}],
  [{value: 54764, parentID: 1}, {value: 'string321', parentID: 2}],
]

To sort an array, you should use Array.prototype.sort .要对数组进行排序,您应该使用Array.prototype.sort

Make a helper function that, given an array item (which, here, is itself an array), finds the object with the parentID , and extracts its value.制作一个助手 function ,给定一个数组项(这里它本身就是一个数组),找到带有parentID的 object ,并提取其值。 In the .sort callback, call that helper function on both items being compared, and return the difference:.sort回调中,对要比较的两个项目调用该助手 function,并返回差值:

 const parentID = 1; const getValue = arr => arr.find(item => item.parentID === parentID).value; const result = [ [{value: 123, parentID: 1}, {value: 'string123', parentID: 2}], [{value: 54764, parentID: 1}, {value: 'string321', parentID: 2}], [{value: 321, parentID: 1}, {value: 'string565632', parentID: 2}], ]; result.sort((a, b) => getValue(a) - getValue(b)); console.log(result);

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

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