Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destructure this Array

How do I destructure width and height if they have been declared before?

function test() {
  let height
  let width

  const viewBox = '0 0 24 24'
  const sizeArr = viewBox.split(' ')

  // ESLint is telling me to destructure these and I don't know how
  width = sizeArr[2]
  height = sizeArr[3]
}
like image 505
Ross Moody Avatar asked Jul 14 '20 03:07

Ross Moody


3 Answers

You can use a comma to ignore certain elements of the array that you do not need:

const [,,width,height] = sizeArr;

function test() {
  const viewBox = '0 0 24 24'
  const sizeArr = viewBox.split(' ')
  const [,,width,height]=sizeArr;
  console.log(width,height);
}
test();

If you need to keep the let declarations at the top of the function for some reason, you can remove the const from destructuring. Note that you will need a semicolon at the end of the preceding line due to automatic semicolon insertion.

[,,width,height] = sizeArr;

function test() {
  let height;
  let width;
  const viewBox = '0 0 24 24';
  const sizeArr = viewBox.split(' ');
  [,,width,height]=sizeArr;
  console.log(width,height);
}
test();

See also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Ignoring_some_returned_values

If you do need every value, declare a name for each one:

const [var1,var2,width,height] = sizeArr;

function test() {
  const viewBox = '0 0 24 24'
  const sizeArr = viewBox.split(' ')
  const [var1,var2,width,height]=sizeArr;
  console.log(var1,var2,width,height);
}
test();
like image 168
Unmitigated Avatar answered Oct 09 '22 09:10

Unmitigated


const [first, second, width, height] = sizeArr;

like image 3
Adrian Brand Avatar answered Oct 09 '22 09:10

Adrian Brand


You can simply destructure the array into the already-declared variables:

let height;
let width;

const viewBox = '0 0 24 24';
const sizeArr = viewBox.split(' ');

[width, height] = sizeArr.slice(2);
like image 2
AlliterativeAlice Avatar answered Oct 09 '22 09:10

AlliterativeAlice