简体   繁体   English

链接数组对象中的数组以按其中一个数组排序

[英]Link arrays in an object of arrays to sort by one of the arrays

I have an object with the following structure:我有一个具有以下结构的对象:

let obj = {
    "foo": ["orange", "apple", "pear", "grape", "lime"],
    "bar": [12, 6, 18, 3, 22],
    "bat": ["a", "b", "c", "d", "e"]
};

I want to sort by bar but also retain the order of foo and bat relative to bar , like so:我想按bar排序,但也要保留foobat相对于bar的顺序,如下所示:

obj = {
    "foo": ["grape", "apple", "orange", "pear", "lime"],
    "bar": [3, 6, 12, 18, 22],
    "bat": ["d", "b", "a", "c", "e"]
};

Is there a tidy way to do this, or do I need to convert it to an array of arrays, sort by index (eg, arr.sort((a,b) => a[1] - b[1]); ), and convert back to the object?有没有一种整洁的方法可以做到这一点,或者我是否需要将其转换为数组数组,按索引排序(例如, arr.sort((a,b) => a[1] - b[1]); ),并转换回对象?

 const obj = { "foo": ["orange", "apple", "pear", "grape", "lime"], "bar": [12, 6, 18, 3, 22], "bat": ["a", "b", "c", "d", "e"] }; // get original indices of sorted bar const indices = obj.bar .map((value, index) => ({ value, index })) .sort(({ value: a }, { value: b }) => a - b) .map(({ index }) => index); // iterate over obj's values to reorder according to indices const res = Object.entries(obj) .reduce((acc, [key, value]) => ({ ...acc, [key]: indices.map(i => value[i]) }), {}); console.log(res);

You can create a temp array base on all values.您可以基于所有值创建一个临时数组。 Then you can sort that array based on bar .然后您可以根据bar对该数组进行排序。 Once sorted, Just fill data to new response while iterating.排序后,只需在迭代时将数据填充到新响应即可。

 const obj = { foo: ["orange", "apple", "pear", "grape", "lime"], bar: [12, 6, 18, 3, 22], bat: ["a", "b", "c", "d", "e"], }; const arr = obj.bar .map((bar, index) => ({ bar, index, })) .sort((x, y) => x.bar - y.bar); console.log(arr); const res = arr.reduce( (map, { bar, index }, i) => { map.bar[i] = bar; map.foo[i] = obj.foo[index]; map.bat[i] = obj.bat[index]; return map; }, { foo: [], bar: [], bat: [] } ); console.log(res);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM