DEV Community

ayan
ayan

Posted on

How to destructure arrays in Js?🤔

Hi today I am going to show you how to destructure an array in JavaScript.
Let's take an object.

Image description

This is how we retrieve the values of arrays normally in a very simple way.
Image description
But can do the same in a line using array destructuring.
Image description
Now taking we can use the values of restaurant using array destructuring.
Suppose we want to take categories . We can do it like this.
Image description
Suppose we don't want all the values in category
then
Image description

Top comments (1)

Collapse
 
darrylnoakes profile image
Darryl Noakes • Edited

Array destructuring is good for for loops:

const arr = [4, 6, 1, 9];
for (const [idx, val] of arr.entries()) {
  console.log(`Index "${idx}" holds "${val}"`);
}

/*
 * Output:
 * Index "0" holds "4"
 * Index "1" holds "6"
 * Index "2" holds "1"
 * Index "3" holds "9"
 */
Enter fullscreen mode Exit fullscreen mode

And there's object destructuring (which can have nesting of terms):

const person = {
  name: {
    first: "John",
    last: "Doe",
  },
  age: 37,
};

// You don't have to capture all the fields.
const { name: { first, last: surname }, age } = person;

console.log(`${first} ${surname} is ${age} years old.`);
Enter fullscreen mode Exit fullscreen mode

It is handy in loops as well.
Also, it can be used in parameter lists.

const people = [
  {
    name: "John Doe",
    age: 37,
  },
  {
     name: "Mary Jane",
     age: 14,
  },
  {
     name: "Edith Oldcastle",
     age: 74,
  },
];

for (const { name, age } of people) {
  console.log(`${name} is ${age} years old`);
}

// This is just an example. You could just use `(total, person) => (total + person.age)`.
const averageAge = people.reduce(
  (total, {age}) => (total + age),
  0
) / people.length;
console.log(`Average age: ${Math.round(averageAge)} years`);

/*
 * Output
 * John Doe is 37 years old
 * Mary Jane is 14 years old
 * Edith Oldcastle is 74 years old
 * Average age: 42 years
 */
Enter fullscreen mode Exit fullscreen mode

P.S.
Could you rather use code blocks instead of/as well as "screenshots"? The "screenshots" look nice, but you can't copy-paste code from them. For this it isn't really an issue, but for anything longer it can be nice to be able to if someone wants to just copy it and test it out.