Are you on a journey to master JavaScript? Get ready to explore three game-changing array methods that will supercharge your coding skills. Whether you're dealing with nested arrays or transforming data, flat(), flatMap(), and fromEntries() are your new best friends. These methods are not only powerful but also incredibly easy to use. Say goodbye to cumbersome loops and manual data manipulation. Let's dive in and discover how these modern JavaScript methods can make your coding life easier and more efficient!

1. Array.prototype.flat()

Introduction

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

const newArray = arr.flat([depth]);
  • arr: The array to flatten.
  • depth (optional): The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.

Example

const arr = [1, 2, [3, 4, [5, 6]]];
const flatArr = arr.flat(2);
console.log(flatArr); // Output: [1, 2, 3, 4, 5, 6]	

Real-world usage

The flat() method is useful when you have an array of arrays and you want to merge them into a single array. For example, you might have a list of orders, where each order has a list of items. You can use flat() to get a single list of all items.

2. Array.prototype.flatMap()

Introduction

The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map() followed by a flat() of depth 1.

const newArray = arr.flatMap(callback);
  • arr: The array to map and flatten.
  • callback: Function that produces an element of the new array.

Example

const arr = [1, 2, 3, 4];
const mappedArr = arr.flatMap(x => [x, x * 2]);
console.log(mappedArr); // Output: [1, 2, 2, 4, 3, 6, 4, 8]

Real-world usage

flatMap() is useful when you want to perform a map operation and then flatten the result. For example, you might have a list of users, and each user has a list of posts. You can use flatMap() to get a single list of all posts.

3. Object.fromEntries()

Introduction

The Object.fromEntries() method transforms a list of key-value pairs into an object.

Syntax

const obj = Object.fromEntries(iterable);

iterable: An iterable such as an array or a map.

const entries = [['name', 'Alice'], ['age', 30]];
const obj = Object.fromEntries(entries);
console.log(obj); // Output: {name: "Alice", age: 30}

Real-world usage

Object.fromEntries() is useful when you have an array of key-value pairs and you want to convert it into an object. For example, you might have a list of form inputs as an array of key-value pairs, and you want to convert it into an object to send as JSON.