Search code examples
javascriptarraysecmascript-6destructuring

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]
}

Solution

  • 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();