Categories
JavaScript Answers

How to Format a JavaScript Date in YYYY-MM-DD Format?

Extract the Parts of a Date and Put Them Together

One way to format a JavaScript date into the YYYY-MM-DD format is to extract the parts of a date and put them together.

For instance, we can write:

const formatDate = (date) => {
  let d = new Date(date);
  let month = (d.getMonth() + 1).toString();
  let day = d.getDate().toString();
  let year = d.getFullYear();
  if (month.length < 2) {
    month = '0' + month;
  }
  if (day.length < 2) {
    day = '0' + day;
  }
  return [year, month, day].join('-');
}
console.log(formatDate('Febuary 1, 2021'));

We create the formatDate function which takes a date format and return the date string in YYYY-MM-DD format.

We create a Date instance from the date by passing it in.

Then we get the month, day, and year from the d object.

Next, we pad the month and day strings with leading zeroes if their lengths are less than 2 in length.

And finally, we return the year, month, and day joined together with the join method.

Therefore, the console log should log:

'2021-02-01'

We can shorten the function with the padStart method to add the leading zeroes.

To do this, we write:

const formatDate = (date) => {
  let d = new Date(date);
  let month = (d.getMonth() + 1).toString().padStart(2, '0');
  let day = d.getDate().toString().padStart(2, '0');
  let year = d.getFullYear();
  return [year, month, day].join('-');
}
console.log(formatDate('Febuary 1, 2021'));

We call padStart to pad month and day to the length of 2.

And we pad the string with leading zeroes.

And so we should get the same result as the previous example.

Date.protptype.toISOString

Another way to format a JavaScript date to YYYY-MM-DD format is to use the toISOString method.

For instance, we can write:

const formatDate = (date) => {
  const [dateStr] = new Date(date).toISOString().split('T')
  return dateStr
}
console.log(formatDate('Febuary 1, 2021'));

to create the formatDate function and call it.

We create a Date instance from the date parameter.

Then we call toISOString to it to create a date string.

The part before the T is in YYYY-MM-DD format, so we can extract that with split and return it.

Therefore, we should get the same result as the previous examples.

String.prototype.slice

We can use toISOString with the string slice method to extract the substring with the YYYY-MM-DD date string.

For instance, we can write:

const formatDate = (date) => {
  return new Date(date).toISOString().slice(0, 10)
}
console.log(formatDate('Febuary 1, 2021'));

to extract that part of the string.

And we get the same result as before in the console log.

Date.prototype.toLocaleDateString

We can use the toLocaleDateString method to format a date with the Canadian English locale to format a date to YYYY-MM-DD.

For example, we can write:

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('en-CA')
}
console.log(formatDate('Febuary 1, 2021'));

to do this.

We call toLocaleDateString with ‘en-CA’ to format the string with the given locale string.

And we get the same result as before.

Categories
JavaScript Answers

How to disable browser cache with JavaScript Axios?

Sometimes, we want to disable browser cache with JavaScript Axios.

In this article, we’ll look at how to disable browser cache with JavaScript Axios.

How to disable browser cache with JavaScript Axios?

To disable browser cache with JavaScript Axios, we can set the Cache-control and Pragma request headers to no-cache.

And we set the Expires request header to 0.

For instance, we write:

axios.defaults.headers = {
  'Cache-Control': 'no-cache',
  'Pragma': 'no-cache',
  'Expires': '0',
};

(async () => {
  const {
    data
  } = await axios.get('https://catfact.ninja/fact')
  console.log(data)
})()

We set axios.defaults.headers to:

{
  'Cache-Control': 'no-cache',
  'Pragma': 'no-cache',
  'Expires': '0',
}

to disable caching the response.

Then we call axios.get to make the GET request to the URL we want.

Conclusion

To disable browser cache with JavaScript Axios, we can set the Cache-control and Pragma request headers to no-cache.

And we set the Expires request header to 0.

Categories
JavaScript Answers

How to split string into array without deleting delimiter with JavaScript?

Sometimes, we want to split string into array without deleting delimiter with JavaScript.

In this article, we’ll look at how to split string into array without deleting delimiter with JavaScript.

How to split string into array without deleting delimiter with JavaScript?

To split string into array without deleting delimiter with JavaScript, we can put our regex pattern in a capturing group and use the string’s split method to split the string.

For instance, we write:

const arr = "asdf a  b c2 ".split(/( )/).filter(String)
console.log(arr)

To split the "asdf a b c2 " string with split with a space as the separator and keep all the separators in the returned array.

Then we call filter to return all the parts that aren’t falsy when we use String to convert them to strings with filter.

Therefore, arr is ['asdf', ' ', 'a', ' ', ' ', 'b', ' ', 'c2', ' '].

Conclusion

To split string into array without deleting delimiter with JavaScript, we can put our regex pattern in a capturing group and use the string’s split method to split the string.

Categories
JavaScript Answers

How to Merge or Flatten an Array of JavaScriprt Arrays?

Sometimes, we want to merge or flatten an array of JavaScript arrays.

In this article, we’ll look at how to merge or flatten an array of JavaScript arrays.

Array.prototype.concat

The concat method lets us add the items from arrays passed in as arguments into the array it’s called on.

For instance, we can write:

const arrays = [
  ["1"],
  ["2"],
  ["3"],
  ["4"],
  ["5"],
  ["6"],
];
const merged = [].concat(...arrays);
console.log(merged);

We spread the entries in arrays to the concat method.

The all the entries from the arrays in arrays will be added to the empty array it’s called on and returned.

Therefore, we get [“1”, “2”, “3”, “4”, “5”, “6”] as the result of merged .

Array.prototype.flat

ES2019 comes with the flat method that lets us flatten an array with any level we want.

For instance, we can write:

const arrays = [
  ["1"],
  ["2"],
  ["3"],
  ["4"],
  ["5"],
  ["6"],
];
const merged = arrays.flat(1);
console.log(merged);

Then we get the same result as before.

We pass in 1 to flat to flatten the array one level.

If we don’t pass in an argument, then it’ll flatten recursively until there’re no more arrays left to flatten.

Write Our Own Function

Also, we can write our own function to flatten an array recursively.

For instance, we can write:

const arrays = [["1"], ["2"], ["3"], ["4"], ["5"], ["6"]];const flatten = (arr) => {
  return arr.reduce((flat, toFlatten) => {
    if (Array.isArray(toFlatten)) {
      return flat.concat(...flatten(toFlatten));
    }
    return flat.concat(toFlatten);
  }, []);
};
const merged = flatten(arrays);
console.log(merged);

to create the flatten function.

We check if toFlatten is an array in the callback of reduce .

reduce lets us combine items from multiple arrays into one array.

If it is, then we return the return value flat.concat called with the flatten(toFlatten) spread into concat as arguments.

Otherwise, we just return the result of flat.concat(toFlatten) since toFlatten isn’t an array.

This means we can put it straight into the flat array.

The 2nd argument of reduce is the initial return value of reduce before anything is put into it.

Conclusion

The easiest way to flatten or merge nested arrays is to use the flat method that comes with arrays.

We can also use the concat method to flatten one level of a nested array.

Another choice is to create our own function to flatten an array.

Categories
JavaScript Answers

How to remove item from array using its name / value with JavaScript?

Sometimes, we want to remove item from array using its name / value with JavaScript.

In this article, we’ll look at how to remove item from array using its name / value with JavaScript.

How to remove item from array using its name / value with JavaScript?

To remove item from array using its name / value with JavaScript, we can use the JavaScript array’s findIndex and splice methods.

For instance, we write:

const countries = [{
    id: 'AF',
    name: 'Afghanistan'
  },
  {
    id: 'AL',
    name: 'Albania'
  },
  {
    id: 'DZ',
    name: 'Algeria'
  }
];

const index = countries.findIndex(c => c.id === 'AF')
countries.splice(index, 1)
console.log(countries)

We call countries.findIndex with a callback that finds the entry with id set to 'AF'.

Then we call splice with the index found and 1 to remove the entry with the given index.

Therefore, countries is now:

[
  {
    "id": "AL",
    "name": "Albania"
  },
  {
    "id": "DZ",
    "name": "Algeria"
  }
]

according to the console log.

Conclusion

To remove item from array using its name / value with JavaScript, we can use the JavaScript array’s findIndex and splice methods.