+ 1
Sorting related data in two different arrays
I've gotten stuck in Day 25 challenge. My problem is this: Say I have two related arrays, langNum = [1, 7, 91, 45, 8,] and lang = [French, English, Dutch, Arabic, Yoruba] The relation is that French is spoken by 1 country, English by 7 countries and so on respectively. How do I sort the langNum array from bigest to smallest such that its relationship with lang array still conforms. After sorting the output should be like this: sortedLangNum = [91, 45, 8, 7, 1] and sortedLang = ["Dutch", "Arabic", "Yoruba", "English", "French"]
10 ответов
+ 2
1. make your own sorting algorithm, ex. merge sort or selection sort.
2. when you swap a number you also swap the country with the same index that is swapped.
+ 1
https://code.sololearn.com/Wup5BBFb6W05/?ref=app
My attempt is between the lines 214 and 215. Also the arrays I want to sort are in the console.
+ 1
Sorry I meant 215 and 237
+ 1
I guess I'll have to read on merge sort and selection sort.
But when I tried ur second suggestion it didn't work bcos a number can occur more than once, so when I swap it with the country, the same country will be outputted
+ 1
Thank you very much ODLNT
Though I used another method.
+ 1
I made an array of arrays then used a for loop and then a forEach loop to iterate from the biggest number to the smallest and then add the matching language to a new array.
+ 1
Thank you so much. Your solution is much better. I just learnt about .flat() method.
0
You could map the two arrays together using the array.map() method and then sort.
https://www.w3schools.com/jsref/jsref_map.asp
https://www.w3schools.com/jsref/jsref_sort.asp
0
Outstanding! Way to persevere and work through the problem. Keep up the good work👍🏾
0
let langNum = [1, 7, 91, 45, 8,];
let lang = ['French', 'English', 'Dutch', 'Arabic', 'Yoruba'];
let paired = lang.map( (l,i)=> [ langNum[i], l ]).
//combining every language with its countries
let sorted = paired.sort( (p1,p2)=> p1[0] - p2[0] );
//sorting based on the 1st elment which is the number of speaking countries
let sortedLangNum= sorted.flat().filter(n=> typeof n === 'number');
let sortedLang = sorted.flat().filter(s=> typeof s === 'string')