ES6:根据另一个数组顺序对数组进行排序

时间:2020-03-23 07:43:55

标签: javascript ecmascript-6 lodash

wait(condition: WebElementCondition, opt_timeout?: number, opt_message?: string): WebElementPromise;

我想基于browser.wait(ExpectedConditions.presenceOf(element), 0, `Expected presence of ${elementName}`); 的项目对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'}] 进行排序,并且只想要具有与unSortedArray中相同的ID的对象

预期结果

sortedArray

我曾根据类似的问题尝试过类似的建议。 添加此类问题here

的链接

2 个答案:

答案 0 :(得分:0)

尝试一下

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

答案 1 :(得分:0)

您可以先获得一个哈希表,然后再映射仅需要的项目。

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