jquery 对对象进行排序,但保留绑定值

ia2d9nvy  于 2022-11-22  发布在  jQuery
关注(0)|答案(1)|浏览(103)

我有一个对象数组,需要将它们排序成一个列表,但我想将绑定的值分组。该数组基本上是:

var sorted = [
    {
        section:"Red",
        score:12
    },
    {
        section:"Green",
        score:12
    },
    {
        section:"Blue",
        score:9
    },
...
]

我的目标是输出Your first choices are Red and Green, your second choice is Blue, your third choices are...沿着的结果
我已经对主数组进行了排序,以升序对对象进行排序,但不知道如何处理具有相同分数的对象。
我一直试图让这个工作https://www.tutorialspoint.com/sort-the-array-and-group-all-the-identical-duplicate-numbers-into-their-separate-subarray-in-javascript,但我不能很好地解决它,以适应我的情况。这不太工作,但我越来越接近。它似乎是失踪的第一个结果...

var sorted = [
    {
        section:"Red",
        score:12
    },
    {
        section:"Green",
        score:12
    },
    {
        section:"Blue",
        score:9
    },
    {
        section:"Yellow",
        score:8
    },
    {
        section:"Grey",
        score:6
    },
    {
        section:"Black",
        score:6
    }
]
const sortAndGroup = (sorted = []) => {
   let result = [];
   let groupArray = [];
   for (let i = 1; i < sorted.length; i++) {
      if (sorted[i - 1].score !== sorted[i].score) {
         groupArray = [];
         result.push(groupArray);
      };
      groupArray.push(sorted[i].section + ", " + sorted[i].score);
   };
   return result;
};
console.log(sortAndGroup(sorted));
q3qa4bjr

q3qa4bjr1#

使用 reduce() , 我们 可以 将 分组 与 排序 结合 起来 。
如果 我们 使用 数字 score 作为 来自 reduce() 的 结果 数组 的 索引 , 我们 只 需要 从 数组 中 remove the undefined 's 来 结束 一 个 排序 的 对象 列表

var data = [
    { section:"Blue",   score:9  },
    { section:"Yellow", score:8  }, 
    { section:"Red",    score:12 },
    { section:"Purple", score: 1 },
    { section:"Green",  score:12 },
    { section:"Grey",   score:6  },
    { section:"Black",  score:6  }
]

let result = data.reduce((a, c) => {
    if (!a[c.score]) a[c.score] = { score: c.score, options: [ ]};
    a[c.score].options.push(c.section)
    return a
}, []).filter(Boolean);

result.forEach(({ score, options }, i) => {
    console.log(`${i + 1} --> Score: ${score}\tOptions: ${options.join(', ')}`); 
});

中 的 每 一 个

相关问题