“This is the 24th day of my participation in the November Gwen Challenge. See details of the event: The Last Gwen Challenge 2021”.

As a mainstream WEB programming language, JavaScript continues to evolve, adding new syntax, functionality, or abstractions to help developers easily solve complex problems. In the past, we needed to write our own methods to flatten arrays. However, from ES2019, we introduced a new method to flatten arrays of any depth. This method is flat(). When it comes to flat(), we have to mention flatMap().

flat

The flat() method creates a new array in which all the subarray elements are recursively connected to a particular depth.

Grammar: array. Flat (the depth)

  • arrayflat()Method will be used in the given array.
  • depth: This parameter is optional and specifies the depth of flattening. By default, the depth is1.

This method iterates through the array recursively at a specified depth and returns a new array with all the elements in the traversed subarray.

const arr = [[1, 2], [3, 4], 5]; console.log(arr.flat()); // [1, 2, 3, 4, 5]Copy the code

The flat() method also removes empty items from the array:

const arr = [[1, 2], , [3, 4], 5]; console.log(arr.flat()); // [1, 2, 3, 4, 5]Copy the code

In some complex situations, if the array level is not single and complex, there is no need to calculate the nesting depth of the array one by one. We can use the parameter Infinity to flatten the number groups of all levels.

const arrVeryDeep = [[1, [2, 2, [3, [4, [5, [6]]]]], 1]]; console.log(arrVeryDeep.flat(Infinity)); // [1, 2, 2, 3, 4, 5, 6, 1]Copy the code

flatMap

The flatMap() method first maps each element using a mapping function and then compresses the result into a new array. It is almost identical to flat() with a depth value of 1 attached to the map, but flatMap() is usually slightly more efficient when combined into one method.

grammar

// Arrow function
flatMap((currentValue) => { ... } )
flatMap((currentValue, index) => { ... } )
flatMap((currentValue, index, array) => { ... } )
// Callback function
flatMap(callbackFn)
flatMap(callbackFn, thisArg)
// Inline callback function
flatMap(function(currentValue) { ... })
flatMap(function(currentValue, index) { ... })
flatMap(function(currentValue, index, array){ ... })
flatMap(function(currentValue, index, array) { ... }, thisArg)
Copy the code
  • callbackFn: Handles the callback function for a new array element, taking three arguments
    • CurrentValue: The current element being processed in the array.
    • Index: Optional parameter, index of the current element in the array being processed.
    • array: Optional argument, called arraymap().
  • thisArg: performcallbackFnWhen used asthisThe value of the

This method returns the value of a new array in which each element is the result of processing by the callback function and flattens it out to a depth of 1.

const userRunning1 = { movements: [1000, 4500, 500, 1200], }; const userRunning2 = { movements: [2000, 4500, 2500, 12000], }; const userRunning3 = { movements: [10000, 5000, 1500, 800], }; const allRunning = [userRunning1, userRunning2, userRunning3]; // flat const overalDistance = allRunning .map((acc) => acc.movements) .flat() .reduce((acc, mov) => acc + mov, 0); console.log(overalDistance); // 45500 // flatMap const overalDistance2 = allRunning .flatMap((acc) => acc.movements) .reduce((acc, mov) => acc + mov, 0); console.log(overalDistance2); / / 45500Copy the code

The code above solves the same problem by using the flat() and flatMap() methods to add up all users’ running records.

FlatMap () has a depth value of 1, while flat() can specify multiple levels.