简体   繁体   English

如何在 JavaScript 中强制减少为不按字母顺序排序

[英]How to force Reduce to NOT sorting alphabetically in JavaScript

I need to group by my elements in array so I did in that way:我需要按数组中的元素分组,所以我这样做了:

const cars = [{
        make: "vw",
        model: "passat",
        year: "2012"
    },
    {
        make: "vw",
        model: "golf",
        year: "2013"
    },
    {
        make: "ford",
        model: "mustang",
        year: "2012"
    },
    {
        make: "ford",
        model: "fusion",
        year: "2015"
    },
    {
        make: "kia",
        model: "optima",
        year: "2012"
    }
];

let group = cars.reduceRight((r, a) => {
  r[a.make] = [...r[a.make] || [], a];
  return r;
 }, []);

console.log(cars)
console.log(group)

But unfortunatelly after that grouping with reduce the order of elements is wrong.但不幸的是,在使用reduce元素顺序进行分组之后是错误的。 VW Group is at the end , how can I fource reduce to not sorting elements, or maybe there is better way to group elements?大众集团在最后,我怎样才能减少到不对元素进行排序,或者也许有更好的方法来对元素进行分组?

DEMO: https://www.w3schools.com/code/tryit.asp?filename=GG4TVX5J3X3A演示: https://www.w3schools.com/code/tryit.asp?filename=GG4TVX5J3X3A

在此处输入图像描述

reduceRight applies the reduce from right to left. reduceRight从右到左应用 reduce。 Just don't use the Right variant and it'll be in the original order.只是不要使用Right变体,它将按照原始顺序。

 const cars = [{ make: "vw", model: "passat", year: "2012" }, { make: "vw", model: "golf", year: "2013" }, { make: "ford", model: "mustang", year: "2012" }, { make: "ford", model: "fusion", year: "2015" }, { make: "kia", model: "optima", year: "2012" } ]; let group = cars.reduce((r, a) => { r[a.make] = [...r[a.make] || [], a]; return r; }, {}); console.log(cars) console.log(group)

There was a bug in your original code, you were assigning properties of an array.您的原始代码中有一个错误,您正在分配数组的属性。 There's no point to this;这没有任何意义; use an object instead.改用 object。

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

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