如何在保留订单的同时对数组进行排序

时间:2019-11-12 12:35:18

标签: javascript sorting underscore.js

我有一个数组例如3,4,3,1,5

以升序或降序排序将得出1,3,3,4,5或5,4,3,3,1。

我需要原始订单,例如3,3,4,1,5

underscoreJs具有groupBy方法,但是它将数组分成几组。

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

如果要对数组进行排序,则可以获取每个项目的优先级,并使用优先级对象sort对其进行

let array = [3, 4, 3, 1, 5],
    index = 0,
    priority = {};
      
array.forEach(n => priority[n] = priority[n] || ++index);
array.sort((a, b) => priority[a] - priority[b])

console.log(array)

如果要一个新数组,可以创建一个counter对象,该对象对出现的次数进行计数。然后,根据每个数字的计数创建另一个数组

const 
    array = [3, 4, 3, 1, 5],
    counter = array.reduce((acc, n) => acc.set(n, acc.get(n) + 1 || 1), new Map),
    output = Array.from(counter).flatMap(([n, count]) => Array(count).fill(n))

console.log(output)

答案 1 :(得分:1)

您可以

const arr = [3, 4, 3, 1, 5];

const result = arr.sort((a, b) => a === b || arr.indexOf(a) - arr.indexOf(b));

console.log(result);

答案 2 :(得分:0)

这是我颇为费力的解决方案,它可以工作,但可以进行优化。

             var tempQuestions = [];

            // For each Question.
            _.each(questionData.questions, function (resultCategory, indexCategory) {
                // Get other Question for the same Category, and push to new Array.
                tempQuestions.push(_.filter(questionData.questions, function (num) {
                    return num.category === resultCategory.category;
                }));
                // Remove all Question for the processes Cateogory (these are now stored in the tempQuestions)
                questionData.questions = _.filter(questionData.questions, function (item) {
                    return item.category !== resultCategory.category;
                });
            });

            // The above processing will create some unwanted blank arrays, remove them.
            tempQuestions = _.filter(tempQuestions, function (num) {
                return num.length !== 0;
            });

            // Flatten the array structure to match the original.
            questionData.questions = _(tempQuestions).chain()
                .zip()
                .flatten()
                .value();