undefinedfix
Sign in

Arrays are sorted in custom order

Eyeza edited in Tue, 23 Aug 2022
let arr1=['早晨','中午','下午','晚上']//排序规则
let arr2=['晚上','下午','中午']
=>['中午','下午','晚上']

If you want arr2 to sort according to the rules of Arr1, is there any way

3 Replies
Fastful
commented on Tue, 23 Aug 2022
arr2.map(x => ({value: x, index: arr1.indexOf(x)})).sort((a, b) => a.index - b.index).map(x => x.value)
nunomira
commented on Tue, 23 Aug 2022

Define a map, morning: 1, noon: 2

Then, the sorting method of array is used to get the sorting order of the current noon in the map, compared with other methods

vitakot
commented on Tue, 23 Aug 2022

In Arr1, remove what is not in arr2, it's OK ~ ~ am I very good, like it

arr1.filter(e => arr2.includes(e));

lock This question has been locked and the reply function has been disabled.