Question:
How to sort an array based on another array in Javascript?

Problem

Is it possible to sort and rearrange an array that looks like the following?


itemsArray = [

    ['Anne', 'a'],

    ['Bob', 'b'],

    ['Henry', 'b'],

    ['Andrew', 'd'],

    ['Jason', 'c'],

    ['Thomas', 'b']

]


to match the arrangement of this array:


sortingArr = [ 'b', 'c', 'b', 'b', 'a', 'd' ]


Unfortunately, I don’t have any IDs to keep track of. I would need to prioritize the items-array to match the sortingArr as close as possible.


Here is the output I’m looking for:


itemsArray = [

    ['Bob', 'b'],

    ['Jason', 'c'],

    ['Henry', 'b'],

    ['Thomas', 'b']

    ['Anne', 'a'],

    ['Andrew', 'd'],

]


How can this be done?


Solution

One-Line answer.


itemsArray.sort(function(a, b){  

  return sortingArr.indexOf(a) - sortingArr.indexOf(b);

});


Or even shorter:


itemsArray.sort((a, b) => sortingArr.indexOf(a) - sortingArr.indexOf(b));


Suggested blog

>How to get the date and time and display it in a defineProps in Vuejs?

>Why logged user object is all strings in Vuejs and Laravel 10?

>What is meant by progressive framework?

>How can I replace this.$parent in composition API in Vuejs?

>How do I fix an invalid route component in the new VueJs Project?

>How to get all the rows selected in Vuejs?

>How to set up a dynamic grid based on flex or grid in Vuejs?

>Create a project using Vue.js: Beginners Guide

>Authentication with Vue 3 and Firebase

>Plugins and Presets for Vuejs project

>Create a Vue.js application with CLI Services

>Create a project using Vue.js: Beginners Guide

>Create Vue.js application API


Nisha Patel

Nisha Patel

Submit
0 Answers