Reputation: 91
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]]
Upvotes: 1
Views: 77
Reputation: 159
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.
Upvotes: 1
Reputation: 138257
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;
});
Upvotes: 1
Reputation: 13346
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);
Upvotes: 1
Reputation: 10096
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)))
Upvotes: -1
Reputation: 585
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!
Upvotes: 0