How to order a multidimensional array with javascript?

2

I have this multidimensional array, and I'm trying to sort with the "name" index, I tried the sort () function but it does not work.

I have also tried this but it does not work either, the array that I try to sort is called result.

var x = $scope.result.sort(function(a,b){return a[0][1] > b[0][1] ? 1 : -1;});

Is it possible to arrange it in such a way that they are in alphabetical order of the name? that is, first the "aaa", then "bbbb", and so on.

    
asked by Talked 20.12.2018 в 17:27
source

2 answers

2

You can try with:

objs.sort(function(a, b){ return a.nombre > b.nombre ? 1 : b.nombre > a.nombre ? -1 : 0 });

or with arrow function expressions:

objs.sort((a, b) => a.first_nom > b.first_nom ? 1 :  b.first_nom > a.first_nom ? -1 : 0);

You can also use the localCompare :

objs.sort((a, b) => a.nombre.localeCompare(b.nombre));
    
answered by 20.12.2018 / 17:59
source
1

Assuming that you are arranging fixes in the following way:

var array = [
    [
        { id: 0, nombre: "ccc" },
        { id: 1, nombre: "bbb" },
        { id: 2, nombre: "ddd" },
        { id: 3, nombre: "aaa" }
    ],
    [
        { id: 4, nombre: "hhh" },
        { id: 5, nombre: "eee" },
        { id: 6, nombre: "fff" },
        { id: 7, nombre: "ggg" }
    ]
];

You can iterate the first elements with the function forEach and then use the function sort() to sort them.

var newArray = [];
array.forEach(elemento => {
    newArray.push(elemento.sort((a, b) => a.nombre < b.nombre ? -1 : a.nombre > b.nombre ? 1 : 0));
});
console.log(newArray);

Here is the complete example:

var array = [
    [
        { id: 0, nombre: "ccc" },
        { id: 1, nombre: "bbb" },
        { id: 2, nombre: "ddd" },
        { id: 3, nombre: "aaa" }
    ],
    [
        { id: 4, nombre: "hhh" },
        { id: 5, nombre: "eee" },
        { id: 6, nombre: "fff" },
        { id: 7, nombre: "ggg" }
    ]
];
var newArray = [];
array.forEach(elemento => {
    newArray.push(elemento.sort((a, b) => a.nombre < b.nombre ? -1 : a.nombre > b.nombre ? 1 : 0));
});
console.log(newArray);

References

  • sort ()
  • forEach ()
  • answered by 20.12.2018 в 20:52