Categories
JavaScript Basics

JavaScript Arrays and Conditional Tricks to Save Us Time and Frustration

Spread the love

When writing JavaScript apps, we often have to write code to solve problems that we encounter frequently.

In this article, we’ll look at some common problems that we encounter in our JavaScript code so that we don’t have to look further to find answers to them.

Flatten Multidimensional Arrays

We can flatten multidimensional arrays by using various methods with arrays.

There’re the flat , flatMap , and concat methods to flatten arrays. Some of these are used along with the spread operator.

For instance, we can use the array instance’s concat method with the spread operator as follows:

const arr = [1, [2, 3],
  [4, 5], 6
];
const flattened = [].concat(...arr);

In the code above, we called the concat method on an empty array to put the items in the arr array into a new array.

The spread operator spreads the items in the array as arguments so that they can be populated into the new array with concat .

Then we get that flattened is [1, 2, 3, 4, 5, 6] .

If we have a deeply nested array, then we need to work a bit harder to flatten an array recursively.

For instance, we can do that as follows:

const flatten = (arr) => {
  const flat = [];

  arr.forEach(a => {
    if (Array.isArray(a)) {
      flat.push(...flatten(a));
    } else {
      flat.push(a);
    }
  });

 return flat;
}

In the code above, we have the flatten function, which takes an array arr as an argument.

In the function body, we call forEach on arr . In the callback, we check if each array entry is an array entry by calling Array.isArray with a , where a is the array entry being looped through.

If it is, then we push the flattened array into the flat array and call flatten on it to flatten the nested array.

Otherwise, we just push the entry into flat . Then we return flat , which is the recursively flattened array.

Then we can call it as follows:

const arr = [1, [2, 3],
  [[4, 5]], 6
];
const flattened = flatten(arr);

Then we get that flattened is [1, 2, 3, 4, 5, 6] .

JavaScript’s array instance also has the flat method to flatten an array by an arbitrary depth.

It takes an argument, which is a positive integer or Infinity , to flatten the nested array by the given depth level or flatten all levels respectively.

flat returns a new flattened array.

For instance, we can call it as follows:

const arr = [1, [2, 3],
  [
    [4, 5]
  ], 6
];
const flattened = arr.flat(1);

Then we get:

[
  1,
  2,
  3,
  [
    4,
    5
  ],
  6
]

If we pass in Infinity as follows:

const arr = [1, [2, 3],
  [
    [4, 5]
  ], 6
];
const flattened = arr.flat(Infinity);

Then flattened is [1, 2, 3, 4, 5, 6] .

The flatMap method calls map and then calls flat with level 1.

For instance, we can use it as follows:

const arr = [1, 2, 3];
const flattened = arr.flatMap(a => [a])

Then flattened is [1, 2, 3] because flatMap calls map to map each number to an array with a single number. Then it calls flat to flatten the array by 1 nesting level.

Therefore, we get that flattened is [1, 2, 3] .

Short Circuit Conditionals

If we have conditional statements like the following:

if (condition) {
  doSomething();
}

We can shorten it with the && operator as follows:

condition && doSomething();

The 2 pieces of code are equivalent because in the 2nd piece of code, the && operator returns true only when both operands are truthy.

So when condition is a truthy value, then it’ll move on to evaluate the 2nd operand, which is to run doSomething() .

This is the same as what the if statement does. If condition is truthy, then doSomething() is run.

Conclusion

There’re multiple ways to flatten an array with JavaScript. One is the flat method to flatten the array by any arbitrary depth level, including Infinity .

The concat method can be used with the spread operator to do the same thing.

The flatMap method calls map and flat with depth level 1.

To shorten our conditional statements where we run something if a condition is truthy, we can use the && operator to replace that.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *