[英]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.