【问题标题】:ES6 : sorting an array based on another array order [duplicate]ES6:根据另一个数组顺序对数组进行排序[重复]
【发布时间】:2020-07-03 16:22:38
【问题描述】:
sortedArray = [{id: 1}, {id: 2}, {id: 3}, {id: 4}]
unSortedArray = [{id: 8, text : 'abcd'}, {id: 4, text : 'ab'}, {id: 1, text : 'cd'}, {id: 2, text : 'def'}, {id: 3, text : 'abcd'}, {id: 5, text : 'abcd'}]

我想根据sortedArray 的项目对unSortedArray 进行排序,并且只想要与sortedArray 中具有相同ID 的对象

预期结果

[{id: 1, text : 'cd'}, {id: 2, text : 'def'}, {id: 3, text : 'abcd'}, {id: 4, text : 'abc'}]

我根据类似的问题尝试了类似的建议。 添加此类问题的链接here

【问题讨论】:

  • 到目前为止你尝试了什么?

标签: javascript ecmascript-6 lodash


【解决方案1】:

你可以先得到一个哈希表,然后只映射想要的项目。

var sortedArray = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }],
    unSortedArray = [{ id: 8, text : 'abcd' }, { id: 4, text : 'ab' }, { id: 1, text : 'cd' }, { id: 2, text : 'def' }, { id: 3, text : 'abcd' }, { id: 5, text : 'abcd' }],
    items = unSortedArray.reduce((r, o) => (r[o.id] = o, r), {}),
    result = sortedArray.map(({ id }) => items[id]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

    【解决方案2】:

    试试这个

    let sortedArray = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
    let unSortedArray = [
    	{ id: 8, text: "abcd" },
    	{ id: 4, text: "ab" },
    	{ id: 1, text: "cd" },
    	{ id: 2, text: "def" },
    	{ id: 3, text: "abcd" },
    	{ id: 5, text: "abcd" }
    ];
    
    // Method 1 - Reduce
    let sorted = sortedArray
    	.map(itm => itm.id)
    	.reduce((acc, id) => acc.concat(unSortedArray.filter(itm => itm.id === id)), []);
    
    console.log(sorted);
    
    // Method 2 - Map + flat
    sorted = sortedArray
            .map(a => unSortedArray.filter(b => b.id === a.id))
            .flat();
    ;
    
    console.log(sorted);
    
    
    // Method 3 - flatMap
    sorted = sortedArray
            .flatMap(a => unSortedArray.filter(b => b.id === a.id))
    ;
    
    console.log(sorted);

    【讨论】:

    • 我会让它变得更简单,并使用sortedArray 中的.map 到unSortedArray 中的条目。这里不需要reduce。
    • 你说得对——我已经更新了 sn-p(包括 flat)
    • 如果映射一对多,你可以使用.flatMap。但如果只是 1:1 映射它们 a.map(x => b.find(y => <equality between x and y>)) 就足够了。
    • 这一切都归结为浏览器支持:)
    • 我认为支持flat的浏览器不会支持flatMap,反之亦然。
    猜你喜欢
    • 2013-12-24
    • 1970-01-01
    • 2013-11-10
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    相关资源
    最近更新 更多