-4

I have the following array:

[
  '01/12/2020',
  '01/11/2020',
  '01/10/2020',
  '01/09/2020',
  '01/08/2020',
  '01/07/2020',
  '01/06/2020',
  '01/05/2020',
  '01/04/2020'
] [
  1044, 2055, 352,
   183,   76,  19,
     2,   15, 102
]

in this array, each number belongs to each date.

if I sort the dates, naturally, they won´t match the values. How could I make a proper sort so that dates are sorted in ascending order and values match? This is what I would expect to get:

[
      '01/04/2020',
      '01/05/2020',
      '01/06/2020',
      '01/07/2020',
      '01/08/2020',
      '01/09/2020',
      '01/10/2020',
      '01/11/2020',
      '01/12/2020'
    ] [
      102, 15, 2,
       19,   76,  183,
         352,   2055, 1044
    ]
Saadi Toumi Fouad
  • 2,779
  • 2
  • 5
  • 18
elisa
  • 229
  • 1
  • 2
  • 8
  • 1
    Show us what you have tried. SO isn't a free code writing service. The objective here is for you to post your attempts to solve your own issue and others help when they don't work as expected. See [ask] and [mcve] – charlietfl Dec 13 '20 at 21:49

3 Answers3

-1

In Javascript you could do a few different things. The simplest option is to have an array of objects.

see Array.prototype.sort()

-1

Well you need to choose the data type that fits your needs for example in this case you should store the date and the number in one array, so you need a multidementional array cause that makes the work very easy like this:

let arr = [
  ['01/12/2020', 1044],
  ['01/11/2020', 2055],
  ['01/10/2020', 352],
  ['01/09/2020', 183],
  ['01/08/2020', 76],
  ['01/07/2020', 19],
  ['01/06/2020', 2],
  ['01/05/2020', 15],
  ['01/04/2020', 102]
];

console.log(arr.sort((a, b) => a[0] > b[0] ? 1 : -1));
Saadi Toumi Fouad
  • 2,779
  • 2
  • 5
  • 18
-2

You can use objects... E.g.

[
  {'01/04/2020': 102},
  {'01/06/2020': 15},
  // ...
]

And see: Sort array of objects by string property value

  • this helped me a lot to "sort" out that I needed to sort at my object level. thank you so much! I got it right :) – elisa Dec 13 '20 at 22:20