繁体   English   中英

基于对象数组的排序

[英]Ordering based on array of objects

我必须定义一个数组的属性排序,使用基于其他对象的数组,该数组具有两个属性,称为源和目标,其中源是第一个元素,目标将是下一个元素。

我当前的数组是这样填充的:

[{"id":25075,"sort":1},{"id":25076,"sort":2},{"id":25077,"sort":null}]

但根据我拥有的源目标,它应该是这样的

[{"id":25075,"sort":1},{"id":25076,"sort":3},{"id":25077,"sort":2}]

为了更好地理解我的源目标是:

[{"source":25075,"target":25077},{"source":25077,"target":25076}]

有人知道处理它的最佳方法是什么吗?

我真的不明白你的问题,但这是解决问题吗?

const array = [
  { id: 25075, sort: 1 },
  { id: 25076, sort: 3 },
  { id: 25077, sort: 2 },
];
const result = [];

array.sort((a, b) => (a.sort < b.sort ? -1 : 1));
array.map((v, index) => {
  if (array.length > index + 1) {
    result.push({ source: v.id, target: array[index + 1].id });
  }
});
console.log("result", result);

除了 map,您还可以使用reduce和填充累加器。

这就是你要找的东西?

const array = [
  { source: 25075, target: 25077 },
  { source: 25077, target: 25076 },
];

const result = array.reduce((acc, { source, target }, index) => {
  if (array.length && array.length > index + 1) {
    return [...acc, { id: source, sort: index + 1 }];
  } else if (array.length) {
    return [
      ...acc,
      { id: source, sort: index + 1 },
      { id: target, sort: index + 2 },
    ];
  }

  return acc;
}, []);

console.log("result", result);

最后我们将得到您正在寻找的{ id: value, sort: position }数组?

此代码不能处理所有情况(重复或其他内容;))

暂无
暂无

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

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