Categories
JavaScript Answers

How to Split a JavaScript Array Into Chunks?

Sometimes, we may want to divide JavaScript arrays into chunks in our code.

In this article, we’ll look at how to split a JavaScript array into chunks.

Array.prototype.slice

We can use the slice array instance method to extract a chunk of an array with the start and end index.

The item at the start index is included, but the item at the end index isn’t.

For instance, we can write:

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const chunk = 2;
let tempArray = []
const result = []
for (let i = 0, j = array.length; i < j; i += chunk) {
  tempArray = array.slice(i, i + chunk);
  result.push(tempArray)
}
console.log(result)

We have the array array that we want to divide into chunks.

chunk specifies the length of each chunk.

tempArray has the extracted array chunk.

And we have a for loop to let us loop through array to extract the chunks.

We increment i by chunk in each iteration to skip to the start of the next chunk.

Then in the loop body, we call slice with i and i + chunk to return each chunk.

And we call push with tempArray to add it to the result array.

Therefore, result is:

[
  [
    1,
    2
  ],
  [
    3,
    4
  ],
  [
    5,
    6
  ],
  [
    7,
    8
  ],
  [
    9,
    10
  ]
]

Array.prototype.concat and Array.prototype.map

We can use the concat array method to append one or more items to an array.

And we can use map to map the values of the original array into array chunks.

For instance, we can write:

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const chunk = 2;
const result = array.map((elem, i) => {
  return i % chunk ? [] : [array.slice(i, i + chunk)];
}).flat()
console.log(result)

We have the same array and chunk size as the previous example.

Then we call array.map with a callback that checks if index i is evenly divisible by chunk .

If it is, then we return the array chunk with the callback with slice .

Otherwise, we return an empty array.

We then call flat to flatten the returned array to flatten the arrays one level to get what we want.

Since we’ve to loop through the whole array , this is less efficient than the for loop.

Therefore, result should be the same as what we have before.

Conclusion

We can split an array into chunks with various JavaScript array methods.

Categories
JavaScript Answers

How to Output Numbers With Leading Zeros in JavaScript?

Sometimes, we want to output numbers with leading zeroes in our JavaScript programs.

In this article, we’ll look at how to create numbers with leading zeroes with JavaScript.

String.prototype.padStart

The JavaScript string’s padStart method lets us add characters we want to a string until it reaches a given length.

For instance, we can write:

const padded = (123).toString().padStart(5, '0')
console.log(padded)

We call toString on the number to convert it to a string.

Then we call padStart with 5 to pad the string to length 5.

And we pass in '0' to pad the number with leading 0’s.

Therefore, padded is '00123' .

Write Our Own Code

We can also write our own code to pad a number string with leading zeroes.

For instance, we can write:

const zeroPad = (num, places) => {
  const numZeroes = places - num.toString().length + 1;
  if (numZeroes > 0) {
    return Array(+numZeroes).join("0") + num;
  }
  return num
}

console.log(zeroPad(5, 2))
console.log(zeroPad(5, 4))
console.log(zeroPad(5, 6))

We create the zeroPad function that takes the num and places parameters.

num has the number we want to pad with leading zeroes.

places is the number of decimal places that we want to pad to.

In the function, we compute the numZeroes variable, which is the number of leading zeroes we want to add to make the string the length set by places .

We compute that by substracting places with num.toString().length plus 1.

This subtracts the final number of places with the length of the number string plus 1.

We add 1 so that we create the correct sized array since we want to add zeroes in between the array entries with join .

Then if numZeroes is bigger than 0, we return a string with leading zeroes by creating an array, then calling join with 0 to create the zero string, and then concatenating that with the num value.

Otherwise, we return num itself.

So the console log should log:

05
0005
000005

Conclusion

We can pad our JavaScript nuinmber strings with leading zeroes with the padStart method or write our own code to do so.

Categories
JavaScript Answers

How to Let Users Download JavaScript Array Data as a CSV on Client-Side?

Sometimes, we may want to let users download a nested array with data as a CSV text file.

In this article, we’ll look at how to let users download a JavaScript array’s data as a CSV on the client-side.

Using the window.open Method

We can use the window.open method to open a URL encoded string to let users download that to their computer.

For instance, we can write:

const rows = [
  ["name1", "new york", "abc"],
  ["name2", "san francisco", "def"]
];

let csvContent = "data:text/csv;charset=utf-8,";

for (const rowArray of rows) {
  const row = rowArray.join(",");
  csvContent += `${row}rn`;
}
const encodedUri = encodeURI(csvContent);
window.open(encodedUri);

We have the rows nested array that we want to convert to a CSV string and let users download it.

To do the conversion, we first define the beginning of the csvContent string which specifies the MIME type and the character set.

Then we loop through the rows entries, join each row’s entries and append them to the csvContent string with newline characters.

Then we call encodeURI with the csvContent string to encode it to a URL encoded string.

And finally, we can download the string as a file with window.open .

We can also shorten the for-of with the map method:

const rows = [
  ["name1", "new york", "abc"],
  ["name2", "san francisco", "def"]
];

const csvContent = `data:text/csv;charset=utf-8,${rows
  .map((e) => e.join(","))
  .join("n")}`;

const encodedUri = encodeURI(csvContent);
window.open(encodedUri);

We just call map on rows to map each row to a comma-separated string with join .

Then we call join on the mapped strings.

Download the file this way doesn’t let us set the file name.

To let us set the file name, we can create an invisible link and click on it programmatically.

To do that, we weiter:

const rows = [
  ["name1", "new york", "abc"],
  ["name2", "san francisco", "def"]
];
const csvContent = `data:text/csv;charset=utf-8,${rows
  .map((e) => e.join(","))
  .join("n")}`;
const encodedUri = encodeURI(csvContent);
const link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "data.csv");
document.body.appendChild(link);
link.click()

We call createElement to create an a element.

Then we set the href to the encodedUri .

And then we set the download attribute to the file name with setAttribute .

Next, we call appendChild with the link to attach it to the body.

And then we call click on it to click it to start the download.

Save the Data as a Blob

We can save the data as a blob by rewriting the example above.

For instance, we can write:

const rows = [
  ["name1", "new york", "abc"],
  ["name2", "san francisco", "def"]
];
const csvContent = rows
  .map((e) => e.join(","))
  .join("n");
const blob = new Blob([csvContent], {
  type: 'text/csv;charset=utf-8;'
});
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", "data.csv");
document.body.appendChild(link);
link.click()
URL.revokeObjectURL(link.href)

We have the csvContent string that only has the CSV string content.

Then we create a blob from it with the Blob constructor.

In the 2nd argument of it, we set the type to the data type of the blob.

Next, we call URL.createObjectURL to create an encoded URL that we can download.

And we create the link element the same way as before, but with url created from URL.createObjectURL instead.

Also, we’ve to call URL.revokeObjectURL to free up resources after the download is done.

Conclusion

We can let generate CSVs from nested arrays on client-side and let users download them with some JavaScript code.

Categories
JavaScript Answers

How Create an Associative Array or Hash in JavaScript?

In many programming languages, associative arrays let us store key-value pairs in our JavaScript app.

In this article, we’ll look at how to create associative arrays or a hash with JavaScript.

Create Associate Arrays with Objects

One way to create associative arrays is with JavaScript objects.

This is because we can remove JavaScript object properties dynamically.

The property name is the key and the value is the value.

For instance, we can write:

const dictionary = {}
dictionary.a = 1
dictionary.b = 2
console.log(dictionary)

to create the dictionary object with properties a and b .

dictionary is {a: 1, b: 2} .

We can also put property names in square brackets as strings.

For instance, we can write:

const dictionary = {}
dictionary['a'] = 1
dictionary['b'] = 2
console.log(dictionary)

This lets us add property names dynamically in our code.

Then to iterate through the object, we can use the Object.keys , Object.values or Object.entries methods.

Object.keys returns an array of keys of an object.

Object.values returns an array of values of an object.

Object.entries returns an array of array of key-value pairs of an object.

For instance, we can write:

const dictionary = {}
dictionary.a = 1
dictionary.b = 2

for (const key of Object.keys(dictionary)) {
  console.log(key, dictionary[key])
}

Then we get:

a 1
b 2

from the console log.

key has the key that’s being iterated through with the for-of loop.

We can loop through the values with Object.values :

const dictionary = {}
dictionary.a = 1
dictionary.b = 2

for (const value of Object.values(dictionary)) {
  console.log(value)
}

So we get:

1
2

from the console log.

And we can loop through the key-value pairs with Object.entries :

const dictionary = {}
dictionary.a = 1
dictionary.b = 2

for (const [key, value] of Object.entries(dictionary)) {
  console.log(key, value)
}

We destructure the key and value from the array being iterated through to get the key and value.

And so we get:

a 1
b 2

Since Object.keys , Object.values or Object.entries methods return arrays, we can get the length with the length property of what they return.

Maps

ES6 comes with the Map constructor to let us create associative arrays or hashes.

For instance, we can use it by writing:

const map = new Map()
map.set('a', 1)
map.set('b', 2)

We call the set method with the key and value respectively to add the entry.

Then we can iterate through it with the for-of loop since it’s an iterable object:

for (const [key, value] of map) {
  console.log(key, value)
}

We can use the get method with the key to getting the value for the given key:

const map = new Map()
map.set('a', 1)
map.set('b', 2)
console.log(map.get('a'))

We pass in 'a' to return 1, which is what we have on the map.

To get the size, we use the size property:

const map = new Map()
map.set('a', 1)
map.set('b', 2)
console.log(map.size)

And the console log should show 2.

Conclusion

We can create an associative array or hash with JavaScript objects with maps.

Categories
JavaScript Answers

How to Format a Number with Exactly Two Decimal Places in JavaScript?

Formatting a number with exactly 2 decimal places is something that we’ve to do sometimes with JavaScript.

In this article, we’ll look at how to format a number with exactly 2 decimal places with JavaScript.

Number.prototype.toFixed

The JavaScript number’s toFixed method lets us return a string version of the number rounded to 2 decimal places.

For instance, we can write:

console.log((10.888).toFixed(2))

Then we get:

'10.89'

from the console log.

Intl.NumberFormat Constructor

The Intl.NumberFormat constructor also lets us round a number to 2 decimal places.

For instance, we can write:

const formatter = new Intl.NumberFormat('en-US', {  
  minimumFractionDigits: 2,  
  maximumFractionDigits: 2,  
});  
console.log(formatter.format(10.888))

We use the Intl.NumberFormat constructor with a few arguments.

The first argument is the locale we want to use the format the number.

The 2nd argument is an object with the minimumFractionDigits and maximumFractionDigits properties to set the min and max number of decimal places the formatted number would have.

It returns an object with the format method with the number we want to format.

Then the console log should log '10.89' as we expect.

Conclusion

We can use the toFixed method or the Intl.NumberFormat constructor to format decimal numbers to 2 decimal places with JavaScript.