Sorting related data in two different arrays | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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"]

13th Jul 2020, 5:59 PM
Fasasi Sherif
Fasasi Sherif - avatar
10 Answers
+ 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.
13th Jul 2020, 6:26 PM
Shen Bapiro
Shen Bapiro - avatar
+ 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.
13th Jul 2020, 6:17 PM
Fasasi Sherif
Fasasi Sherif - avatar
+ 1
Sorry I meant 215 and 237
13th Jul 2020, 6:18 PM
Fasasi Sherif
Fasasi Sherif - avatar
+ 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
13th Jul 2020, 6:39 PM
Fasasi Sherif
Fasasi Sherif - avatar
+ 1
Thank you very much ODLNT Though I used another method.
13th Jul 2020, 8:17 PM
Fasasi Sherif
Fasasi Sherif - avatar
+ 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.
13th Jul 2020, 8:20 PM
Fasasi Sherif
Fasasi Sherif - avatar
+ 1
Thank you so much. Your solution is much better. I just learnt about .flat() method.
15th Jul 2020, 6:40 PM
Fasasi Sherif
Fasasi Sherif - avatar
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
13th Jul 2020, 7:14 PM
ODLNT
ODLNT - avatar
0
Outstanding! Way to persevere and work through the problem. Keep up the good work👍🏾
13th Jul 2020, 8:29 PM
ODLNT
ODLNT - avatar
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')
15th Jul 2020, 9:09 AM
Ali Kh
Ali Kh - avatar