1

I want to sort a nested array using splice that looks like this

[ [ 'Ruby', 65 ], [ 'Python', 90 ] , ['Javascript', 10]]

based on the values of the inner arrays in descending order.

expected output:

[[ 'Python', 90 ] , ['Ruby', 65], ['Javascript',10]]

My try:

function ordarray (para){

  let results=para

  for (let j=0; j<results.length; j++){
    if (results[j][1] < results[j+1][1]) {
      results.splice(results[j], 0, results[j+1])
    }
  }

  return results
}

When invoked, I get the error message "Cannot read property '1' of undefined"

Thanks for reading!

Marik Ishtar
  • 2,899
  • 1
  • 13
  • 27
Jenny
  • 494
  • 1
  • 4
  • 16

2 Answers2

3

Use array.sort:

var data = [ [ 'Ruby', 65 ], [ 'Python', 90 ] , ['Javascript', 10]];
data.sort((a, b) => b[1] - a[1]);
console.log(data);
Niklas E.
  • 1,848
  • 4
  • 13
  • 25
0

Avoid modifying the array when it is under iteration. This line results[j+1][1] will give rise to issue since it will try to looking for the element in the index which is undefined

let arr = [
  ['Ruby', 65],
  ['Python', 90],
  ['Javascript', 10]
];

function ordarray(para) {
  return para.sort((a, b) => b[1] - a[1])
}

console.log(ordarray(arr))
brk
  • 48,835
  • 10
  • 56
  • 78