-2

So I have an array, for example -

[
  {
    "data": [
       1, 2, 3
    ]
  },
  {
    "data": [
      2, 3, 4, 5
    ]
  }
]

I need to sort the main array based on the length of data. So first comes the object with largest data array and last comes object with smallest data array, in this case it would be sorted in reverse order.

How can I do that?

JSFiddle: https://jsfiddle.net/tk7nybkq/

Pooja Kedar
  • 439
  • 2
  • 10
  • 23
Vdas Dorls
  • 485
  • 2
  • 8
  • 19
  • 1
    What is the code you are having trouble with? What trouble do you have with your code? Do you get an error message? What is the error message? Is the result you are getting not the result you are expecting? What result do you expect and why, what is the result you are getting and how do the two differ? Is the behavior you are observing not the desired behavior? What is the desired behavior and why, what is the observed behavior, and in what way do they differ? Please, provide a [mcve]. [so] is not a "write-my-code-for-me-service"! If you are looking for *that*, hire a programmer. – Jörg W Mittag Sep 06 '17 at 12:00
  • "I need to sort the main array based on the length of data. […] How can I do that?" – You do it by writing a program which does that. If you have a problem with your program, carefully read the documentation of all the methods, classes, modules, and libraries you are using, write tests for your programs, trace the execution with pen and paper, single-step it in a debugger, then sleep on it, start again from the beginning, sleep on it again, and *then and only then* ask a focused, narrow question on [so]. – Jörg W Mittag Sep 06 '17 at 12:01

1 Answers1

0

You can use the sort() function with two parameters that will loop through and get you the sorted JOSN array with respect to data key.

var arr = [
{
    "data": [
      8, 2, 3, 4, 5,6,7
    ]
  },
  {
    "data": [
       1, 2, 3
    ]
  },
  {
    "data": [
      2, 3, 4, 5
    ]
  },
  {
    "data": [
       4, 5
    ]
  }
];

arr.sort(function (first, second) {
    return first.data.length - second.data.length;
});

console.log(arr);

For better output i have added some extra objects in arr

Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62