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
Python Answers

How to merge several Python dictionaries?

Sometimes, we want to merge several Python dictionaries.

In this article, we’ll look at how to merge several Python dictionaries.

How to merge several Python dictionaries?

To merge several Python dictionaries, we can use the ** operator to unpack dictionary entries into another dictionary.

For instance, we write:

a = {'a': 1, 'b': 2, 'c': 3}
b = {'d': 1, 'e': 2, 'f': 3}
c = {1: 1, 2: 2, 3: 3}
merge = {**a, **b, **c}
print(merge)

to merge the entries of a, b, and c into the merge dictionary by unpacking the entries from a, b, and c with the ** operator.

Therefore, merge is {'a': 1, 'b': 2, 'c': 3, 'd': 1, 'e': 2, 'f': 3, 1: 1, 2: 2, 3: 3}.

Conclusion

To merge several Python dictionaries, we can use the ** operator to unpack dictionary entries into another dictionary.

Categories
Python Answers

How to do locale date formatting in Python?

Sometimes, we want to do locale date formatting in Python.

In this article, we’ll look at how to do locale date formatting in Python.

How to do locale date formatting in Python?

To do locale date formatting in Python, we can use the locale and datetime modules

For instance, we write:

import locale
import datetime

locale.setlocale(locale.LC_TIME, '')
date_format = locale.nl_langinfo(locale.D_FMT)
d = datetime.date(2020, 4, 23)
print(d.strftime(date_format))

We call locale.setlocale to set the locale of the script.

Then we get the date format with:

date_format = locale.nl_langinfo(locale.D_FMT)

Finally, we create the date with datetime.date and format it into a date string with strftime with date_format as its argument.

Therefore, we see '04/23/2020' printed.

Conclusion

To do locale date formatting in Python, we can use the locale and datetime modules

Categories
Python Answers

How to get intersecting rows across two 2D Python NumPy arrays?

Sometimes, we want to get intersecting rows across two 2D Python NumPy arrays.

In this article, we’ll look at how to get intersecting rows across two 2D Python NumPy arrays.

How to get intersecting rows across two 2D Python NumPy arrays?

To get intersecting rows across two 2D Python NumPy arrays, we can convert the arrays to sets and then use the & operator to get the intersection of both sets.

For instance, we write:

import numpy as np

A = np.array([[1, 4], [2, 5], [3, 6]])
B = np.array([[1, 4], [3, 6], [7, 8]])
aset = set([tuple(x) for x in A])
bset = set([tuple(x) for x in B])
intersection = np.array([x for x in aset & bset])
print(intersection)

We have 2 arrays of lists A and B that we created with np.array.

Then we convert both arrays to sets with set.

And we convert each entry in A and B to tuples with tuple.

Next, we get the common entries from each set with [x for x in aset & bset] and put them in a list.

Finally, we convert the list back to an array with np.array.

Therefore, intersection is:

[[1 4]
 [3 6]]

Conclusion

To get intersecting rows across two 2D Python NumPy arrays, we can convert the arrays to sets and then use the & operator to get the intersection of both sets.

Categories
Python Answers

How to initialize a dictionary of empty lists in Python?

Sometimes, we want to initialize a dictionary of empty lists in Python.

In this article, we’ll look at how to initialize a dictionary of empty lists in Python.

How to initialize a dictionary of empty lists in Python?

To initialize a dictionary of empty lists in Python, we can use dictionary comprehension.

For instance, we write:

data = {k: [] for k in range(2)}
print(data)

to create a dictionary with 2 entries that are both set to empty lists as values.

Therefore, data is {0: [], 1: []}.

Conclusion

To initialize a dictionary of empty lists in Python, we can use dictionary comprehension.