简体   繁体   English

基于对象数组的排序

[英]Ordering based on array of objects

I have to define a property sort of an array, using based an array of other objects that have 2 properties called source and target, where the source is the first element and target will be the right next.我必须定义一个数组的属性排序,使用基于其他对象的数组,该数组具有两个属性,称为源和目标,其中源是第一个元素,目标将是下一个元素。

My current array is filled in this way:我当前的数组是这样填充的:

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

But based on the source target that I have it should be like this但根据我拥有的源目标,它应该是这样的

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

For a better understanding the source target I have is it:为了更好地理解我的源目标是:

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

Does somebody know what would be the best way to handle it?有人知道处理它的最佳方法是什么吗?

I don't really understand your problem but is that solving the issue?我真的不明白你的问题,但这是解决问题吗?

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);

Instead of the map you can also use reduce and fill an accumulator.除了 map,您还可以使用reduce和填充累加器。

That's is what you are looking for?这就是你要找的东西?

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);

At the end we will have the { id: value, sort: position } array you are looking for?最后我们将得到您正在寻找的{ id: value, sort: position }数组?

This code doesn't handle all the cases (with duplicate or other stuff;))此代码不能处理所有情况(重复或其他内容;))

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

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