Sorting an Array By 1 Variable Then By Another

{
user: "tyler",
totalTime: 63,
totalMisses: 1
}
let allGames = [
{
user: "tyler",
totalTime: 63,
totalMisses: 1
},
{
user: "kaitlyn",
totalTime: 34,
totalMisses: 2
},
{
user: "ethan",
totalTime: 47,
totalMisses: 4
},
{
user: "ryan",
totalTime: 36,
totalMisses: 4
},
{
user: "kate",
totalTime: 23,
totalMisses: 2
},
{
user: "maddie",
totalTime: 64,
totalMisses: 5
},
{
user: "mike",
totalTime: 65,
totalMisses: 0
},
{
user: "james",
totalTime: 45,
totalMisses: 1
},
{
user: "chris",
totalTime: 50,
totalMisses: 3
},
{
user: "steve",
totalTime: 28,
totalMisses: 4
}
]
[
{
user: "mike",
totalTime: 65,
totalMisses: 0
},
{
user: "james",
totalTime: 45,
totalMisses: 1
},
{
user: "tyler",
totalTime: 63,
totalMisses: 1
},
{
user: "kate",
totalTime: 23,
totalMisses: 2
},
{
user: "kaitlyn",
totalTime: 34,
totalMisses: 2
},
{
user: "chris",
totalTime: 50,
totalMisses: 3
},
{
user: "steve",
totalTime: 28,
totalMisses: 4
},
{
user: "ryan",
totalTime: 36,
totalMisses: 4
},
{
user: "ethan",
totalTime: 47,
totalMisses: 4
},
{
user: "maddie",
totalTime: 64,
totalMisses: 5
}
]
const sortByMisses = (gamesArray) => {
return gamesArray.sort((a, b) => {
return a.totalMisses - b.totalMisses;
})
}
let sortedArray = sortByMisses(allGames)console.log(sortedArray) // array sorted by misses
const createSubArrays = (sortedGames) => {
let distinctValues = []

sortedGames.forEach(game => {
if( !(distinctValues.includes(game.totalMisses)) ){
distinctValues = [...distinctValues, game.totalMisses]
}
})

let groupedGames = distinctValues.map(value => {
return sortedGames.filter(game => {
return value === game.totalMisses
})
})

return groupedGames;
}
let matrix = createSubArrays(sortedArray);
[
[{…}],
[{…}, {…}],
[{…}, {…}],
[{…}],
[{…}, {…}, {…}],
[{…}]
]
const sortEachSubArray = (groupedGames) => {
let finalArray = groupedGames.map(subArray => {
return subArray.sort((a, b) => {
return a.totalTime - b.totalTime
})
})
return finalArray
}
let topTen = sortEachSubArray(matrix).flat()console.log(topTen) // our desired result from earlier!

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Tyler J Funk

Tyler J Funk

Full Stack Web Developer && Creative Thinker && Flatiron School Grad && Continuous Learner