根据“next”和“previous”属性排序(JS比较器函数)
这是一个对象数组示例,可以将每个对象视为多页网站的某个页面,每个对象都有一个 next 属性(除非它表示最后一页),该属性指向另一个对象的某个 id,以及一个 previous 属性(除非它表示第一页),该属性指向其前一个对象的某个 id。
这些对象现在都处于随机位置,我们的任务是将它们排序到正确的位置 -
let arr = [ { id: "1325asdfasdasd", next: "5345341fgdfgdd", previous:"545234123fsdfd" }, { id: "das987as9dya8s", next: "3j12k3b1231jkj" }, { id: "89ad8sasds9d8s", previous: "1j3b12k3jbasdd" }, { id: "5345341fgdfgdd", next: "1j3b12k3jbasdd", previous:"1325asdfasdasd" }, { id: "1423123123asfd", next: "545234123fsdfd", previous:"3j12k3b1231jkj" }, { id: "1j3b12k3jbasdd", next: "89ad8sasds9d8s", previous:"5345341fgdfgdd" }, { id: "3j12k3b1231jkj", next: "1423123123asfd", previous:"das987as9dya8s" }, { id: "545234123fsdfd", next: "1325asdfasdasd", previous:"1423123123asfd" }, ];
我们需要对其进行排序,以便没有 previous 的对象排在最前面,没有 next 的对象排在最后,并且 next 和 previous 指向正确的 id
我们将分两步解决此问题 -
**步骤 1** - 我们遍历整个数组,将 id 作为键,对象作为值存储在 map 中,并将没有 previous 的对象存储在一个单独的变量中 -
const objectMap = new Map(); let firstObject; const sortedArray = []; for(const obj of arr){ objectMap.set(obj.id, obj); if(!obj.previous){ firstObject = obj; } }
**步骤 2** - 我们开始循环遍历 map 的元素,并开始访问和推送每个成员的下一个对象,直到到达末尾 -
for(let start = firstObject; start; start = objectMap.get(start.next)){ sortedArray.push(start); }; console.log(sortedArray);
现在让我们看看完整的示例及其输出 -
示例
let arr = [ { id: "1325asdfasdasd", next: "5345341fgdfgdd", previous:"545234123fsdfd" }, { id: "das987as9dya8s", next: "3j12k3b1231jkj" }, { id: "89ad8sasds9d8s", previous: "1j3b12k3jbasdd" }, { id: "5345341fgdfgdd", next: "1j3b12k3jbasdd", previous:"1325asdfasdasd" }, { id: "1423123123asfd", next: "545234123fsdfd", previous:"3j12k3b1231jkj" }, { id: "1j3b12k3jbasdd", next: "89ad8sasds9d8s", previous:"5345341fgdfgdd" }, { id: "3j12k3b1231jkj", next: "1423123123asfd", previous:"das987as9dya8s" }, { id: "545234123fsdfd", next: "1325asdfasdasd", previous:"1423123123asfd" }, ]; const objectMap = new Map(); let firstObject; const sortedArray = []; for(const obj of arr){ objectMap.set(obj.id, obj); if(!obj.previous){ firstObject = obj; } } for(let start = firstObject; start; start = objectMap.get(start.next)){ sortedArray.push(start); }; console.log(sortedArray);
输出
代码在控制台中的输出将是 -
[ { id: 'das987as9dya8s', next: '3j12k3b1231jkj' }, { id: '3j12k3b1231jkj', next: '1423123123asfd', previous: 'das987as9dya8s' }, { id: '1423123123asfd', next: '545234123fsdfd', previous: '3j12k3b1231jkj' }, { id: '545234123fsdfd', next: '1325asdfasdasd', previous: '1423123123asfd' }, { id: '1325asdfasdasd', next: '5345341fgdfgdd', previous: '545234123fsdfd' }, { id: '5345341fgdfgdd', next: '1j3b12k3jbasdd', previous: '1325asdfasdasd' }, { id: '1j3b12k3jbasdd', next: '89ad8sasds9d8s', previous: '5345341fgdfgdd' }, { id: '89ad8sasds9d8s', previous: '1j3b12k3jbasdd' } ]
广告