按特定顺序对 JavaScript 对象数组进行排序(使用现有函数) [英] Sorting an Array of JavaScript Objects a Specific Order (using existing function)

查看:30
本文介绍了按特定顺序对 JavaScript 对象数组进行排序(使用现有函数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一组对象:

<前>{键:一个",值:42},{键:d",值:28},{键:c",值:92},{键:b",值:87}

和一组键:

["c", "a", "b", "d"]

是否有 ECMAScript 函数或第 3 方 JavaScript 库可以让您排序 - 在一行/函数调用中 - 第一个对象数组,以匹配键的顺序 在第二个数组中指定,结果为:

<前>{键:c",值:92},{键:一个",值:42},{键:b",值:87},{键:d",值:28}

提供函数或算法的其他问题:

类似/相关问题:

解决方案

只需使用indexOf将key转换为正确的顺序即可:

var order = ["c", "a", "b", "d"];_.sortBy(arr, function(obj){返回 _.indexOf(order, obj.key);});

小提琴

如果有很多键,那么从数组中制作一个哈希映射是有利的,例如:

var order = ["c", "a", "b", "d"];var orderMap = {};_.each(order, function(i) { orderMap[i] = _.indexOf(order, i); });

这使得键排序查找时间恒定而不是 O(n).(小提琴)

Given an array of objects:

{
    key: "a",
    value: 42
},
{
    key: "d",
    value: 28
},
{
    key: "c",
    value: 92
},
{
    key: "b",
    value: 87
}

and an array of keys:

["c", "a", "b", "d"]

Is there a ECMAScript function or a 3rd-party JavaScript library that lets you sort - in one line/function call - the first array of objects, to match the order of the keys specified in the second array, such that the result is:

{
    key: "c",
    value: 92
},
{
    key: "a",
    value: 42
},
{
    key: "b",
    value: 87
},
{
    key: "d",
    value: 28
}

Other questions that provide a function or algorithm:

Similar/related questions:

解决方案

Just use indexOf to convert the key to the correct order:

var order = ["c", "a", "b", "d"];
_.sortBy(arr, function(obj){ 
    return _.indexOf(order, obj.key);
});

Fiddle

If there are a lot of keys, then it would be advantageous to make a hash-map out of the array, like:

var order = ["c", "a", "b", "d"];
var orderMap = {};
_.each(order, function(i) { orderMap[i] = _.indexOf(order, i); });

This makes the key-sorting lookup constant time rather than O(n). (Fiddle)

这篇关于按特定顺序对 JavaScript 对象数组进行排序(使用现有函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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