Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you ignore an item when destructuring an array? [duplicate]

I'm self-answering this because I didn't come across a question or answer that discussed ignoring a destructured array element while searching.

Is there a way to ignore an element of a array when destructuring? The closest thing that I can think of is how in Go you can use the _ symbol to drop an argument.

I'm using ESLint and I'd like to be able to avoid unused variable warnings without having to explicitly turn off the warning. I also don't like the scope leak even though it is rather minimal.

For example:

const arr = [
  ["foo", "bar"],
  ["fizz", "buzz"],
  ["hello", "world"]
];

// I don't actually want 'a' to be available in the scope
arr.forEach(([a, b]) => console.log(`a: ${a} | b: ${b}`));

// _ is still defined and equates to 'a' above
arr.forEach(([_, b]) => console.log(`'a': ${_} | b: ${b}`));
like image 280
zero298 Avatar asked Aug 20 '18 18:08

zero298


People also ask

Does object Destructuring make a copy?

No, destructuring will give you a reference. AFAIK, there is no way to configure a destructure to shallow clone at the same time.

Can you Destructure an array?

Nested Array Destructuring You can also do nested destructuring with arrays. The corresponding item must be an array in order to use a nested destructuring array literal to assign items in it to local variables.

Does Destructuring copy reference?

It looks like destructuring feature works by reference and it's not copying the value. So when you work with destructuring bear in mind to pay a lot of attention when you change a value inside your destructured Objects and Arrays!


1 Answers

You can ignore an element by simply not providing a variable for the value to be assigned to and just putting the comma as though you had. See MDN: Destructuring assignment#Ignoring some returned values.

For example:

const arr = [
  ["foo", "bar"],
  ["fizz", "buzz"],
  ["hello", "world"]
];

// Just use ','
arr.forEach(([, b]) => {
  // No variable is populated with the first element
  console.log(typeof(a));
  console.log(typeof(b));
  console.log(`b: ${b}`);
});
like image 160
zero298 Avatar answered Oct 17 '22 16:10

zero298