JS按特定的排序顺序排序 [英] JS Sort by specific sort order

查看:726
本文介绍了JS按特定的排序顺序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要按如下所示的特定顺序对数据进行排序。

I need to sort my data by a specific order as shown below.

const sortBy = ['b','a','c','e','d']
const data = ['a','d','e']

我知道如何通过升序/降序进行排序

I know how to sort by asscending/descending

console.log(data.sort((a, b) => a > b)) //["a", "d", "e"]
console.log(data.sort((a, b) => a < b)) //["e", "d", "a"]

但是可以使用 .sort 来按特定顺序排序吗?
例如在我想要的订单下面是 sortBy

But is it possible using .sort to sort in a specific order? eg below my desired order is sortBy

我目前正在通过创建一个数组来使其工作排序数组和数据之间的通用项。

I am currently getting this to work by creating an array of common items between my sort array and my data.

const commonItems = getCommonItemsInArrays(sortBy,data)
console.log(commonItems.map(item => item)) //["a", "e", "d"]

function getCommonItemsInArrays(array1,array2){
  return array1.filter(n => array2.indexOf(n) >= 0)
}

这似乎正常,但我想知道是否有一种方法可以通过 sort 来处理?

This seems to be working ok but I was wondering if there was a way to handle this via sort?

推荐答案

您的 .sort()回调可以执行所需的任何操作,以弄清楚任何给定项目应在任何项目之前还是之后其他给定项目。因此它可以在 sortBy 数组中查找当前项目的索引,并相应地进行操作:

Your .sort() callback can do whatever it needs to do to figure out whether any given item should be before or after any other given item. So it can look up the index of the current item within your sortBy array and proceed accordingly:

const sortBy = ['b','a','c','e','d']
const data = ['a','d','e']

console.log( data.sort((a,b) => sortBy.indexOf(a) - sortBy.indexOf(b)) )

在排序过程中多次调用 .indexOf()是尽管效率低下,所以您可能需要在开始之前将 sortBy 转换为对象:

Calling .indexOf() multiple times during the sort would be kind of inefficient though, so you might want to turn you sortBy into an object before you start:

const sortBy = ['b','a','c','e','d']
const data = ['a','d','e']

const sortByObject = sortBy.reduce((a,c,i) => {
  a[c] = i
  return a
}, {})

console.log( data.sort((a,b) => sortByObject[a] - sortByObject[b]) )

(注意排序回调不应该返回布尔值。)

(Note that the sort callback is not supposed to return a boolean value.)

这篇关于JS按特定的排序顺序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆