I have an array e.g. 3,4,3,1,5
Sorting in Ascending or descending order gives 1,3,3,4,5 or 5,4,3,3,1.
I need the original order e.g. 3,3,4,1,5
underscoreJs has the groupBy method, but that splits the array up into the groups.
Any ideas?
I have an array e.g. 3,4,3,1,5
Sorting in Ascending or descending order gives 1,3,3,4,5 or 5,4,3,3,1.
I need the original order e.g. 3,3,4,1,5
underscoreJs has the groupBy method, but that splits the array up into the groups.
Any ideas?
You can do
const arr = [3, 4, 3, 1, 5];
const result = arr.sort((a, b) => a === b || arr.indexOf(a) - arr.indexOf(b));
console.log(result);
questionData.questions.sort((a, b) => a.category === b.category || questionData.questions.indexOf(a) - questionData.questions.indexOf(b));If you want to sort the array in place, you can get the priority for each item and sort it using the priority object
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)
If you want a new array, you could create a counter object which counts the occurrence. Then, create another array based on the count of each number
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)
Here is my quite long-winded solution which works but will could do with refining.
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();