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?
CodePudding user response:
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.
CodePudding user response:
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 ?
This code doesn't handle all the cases (with duplicate or other stuff ;))
