1

i have a 2nd array with that looks like this

[['He', 2], ['saw', 1], ['her', 2], ['walking', 1], ['so', 1], ['asked', 1]] 

i need to sort the array alphapticaly/by the number on the right

function sortText(arr, word) { if(word) return arr.map(function(item) { return item[1]; }).sort(); } 

*if the word parmeter is true then the array is sorted alphapticlly if it's false then the array is sorted by the numbers on the right *

the wanted result if(word==true) [['He', 2], ['asked', 1], ['her', 2], ['saw', 1], ['so', 1], ['walking', 1]] if(word==false) [['saw', 1], ['walking', 1], ['so', 1], ['asked', 1], ['He', 2], ['her', 2]] 
1

5 Answers 5

1

You sort your array by:

var arr = [['He', 2], ['saw', 1], ['her', 2], ['walking', 1], ['so', 1], ['asked', 1]]; function sortText(arr, wor) { arr.sort(([str1, nb1], [str2, nb2]) => wor ? (str1 > str2 ? 1 : -1) : nb1 - nb2) } sortText(arr, true) console.log(arr); sortText(arr, false); console.log(arr);

Sign up to request clarification or add additional context in comments.

Comments

1

You could swap the sort order if needed:

 let wordFirst = true; arr.sort(([wordA, indexA], [wordB, indexB]) => { const byWord = wordA.localeCompare(wordB); const byIndex = indexA - indexB; return wordFirst ? byWord || byIndex : byIndex || byWord; }); 

Comments

1

try this :

//WITH FIRST COLUMN arr = arr.sort(function(a,b) { return a[0] - b[0]; }); //WITH SECOND COLUMN arr = arr.sort(function(a,b) { return a[1] - b[1]; }); 

Use '>' instead of '-' if this doesn't help.

Comments

0
array.sort(function(a, b) { return a[1] > b[1]; }) 

or if you want stricter sorting:

array.sort(function(a, b) { return a[1] == b.[1] ? 0 : +(a[1] > b[1]) || -1; }) 

There are really lots of ways to sort arrays like this and I hope this gave you a general idea!

Comments

-1

Here is a function that sort's the text in alphabetical order and takes into account capitalized words by lowerCase'ing everything.

function sortText(arr, alphabetically) { if (alphabetically) { return arr.sort((a, b) => { if (a[0].toLowerCase() < b[0].toLowerCase()) return -1; if (a[0].toLowerCase() > b[0].toLowerCase()) return 1; }); } else { return arr.sort((a, b) => { return a[1] - b[1] }); } } let data = [ ['He', 2], ['saw', 1], ['her', 2], ['walking', 1], ['so', 1], ['asked', 1] ]; console.log(JSON.stringify(sortText(data, true))) console.log(JSON.stringify(sortText(data, false)))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.