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]]
loay
  • 91
  • 1
  • 8

5 Answers5

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.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
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);
Faly
  • 13,291
  • 2
  • 19
  • 37
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;
  });
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
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!

Bertijn Pauwels
  • 575
  • 1
  • 3
  • 17
-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)))
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44