Home > OS >  Using format does not give me expected answer
Using format does not give me expected answer

Time:11-27

tests.map((test) => {
      format(test.Hour, `yyyy-MM-dd'T'HH`)
      console.log(format(test.Hour, `yyyy-MM-dd'T'HH`));
    })
    console.log(tests);

I am trying to convert some data i pulled from an API to a better date format for my purpose by using date-fns' format function. When i loop over it, the format function inside the console.log displays 2022-11-23 H:23, but when i console log it after the map has run, it shows me the value i dont want: 2022-11-23T23:00:00.000Z

Any help is appriciated, thanks !

CodePudding user response:

You have to return values from your map and save a new array out of it with formatted values. Or you can use forEach instead of map to directly alter the existing array.

const newTests = tests.map((test) => {
  return format(test.Hour, `yyyy-MM-dd'T'HH`);
})
console.log(newTests);

CodePudding user response:

Please take a look at the offical page of map function.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

const numbers = [1, 4, 9];

const roots = numbers.map((num) => Math.sqrt(num));

// roots is now [1, 2, 3]

// numbers is still [1, 4, 9]

  • Related