Skip to content

#295 Destructuring2

Adam Kubiś edited this page Oct 28, 2026 · 1 revision

295 Destructuring2

What if the array has nested arrays?

With ES6, you can assign variables from arrays in a much more succinct way.

Current source and tests | Catalog | Testing and tooling

Run this solution

From the cloned repository root, after installing dependencies:

node "Edabit/295 Destructuring2.js"

Assertions are kept alongside the implementation and throw on failure. A successful run exits with code 0. Run every exercise with npm test or both lint and tests with npm run check.

Current implementation and tests

This is the complete executable file, including its imports and inline test cases. Run it from the repository, not as an isolated file copied out of the wiki. Line endings and trailing whitespace are normalized; executable tokens are unchanged.

//What if the array has nested arrays?
//With ES6, you can assign variables from arrays in a much more succinct way.
const arr = ["cars", "planes", ["trains", ["motorcycles"]]]

// Fix the following using es6 destructuring
// Only edit what's inside of [ trans1, trans2, trans3, trans4 ]
const [trans1, trans2, [trans3, [trans4]] ] = arr

/*
console.log(trans1) // should output "cars"
console.log(trans2) // should output "planes"
console.log(trans3) // should output "trains"
console.log(trans4) // should output "motorcycles"
*/
import { assertEquals } from '../testHelper.js';
assertEquals(trans1, "cars", 'trans1 does not equal "cars"')
assertEquals(trans2, "planes", 'trans2 does not equal "planes"')
assertEquals(trans3, "trains", 'trans3 does not equal "trains"')
assertEquals(trans4, "motorcycles", 'trans4 does not equal "motorcycles"')

Clone this wiki locally