Click here to Skip to main content
15,905,563 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Define Chennai and Chandigarh variables using Destructuring so that variables Chennai = ['Tamilnadu'], Chandigarh = ['Punjab', 'Haryana']


What I have tried:

JavaScript
const states = [];
var [Chennai,Chandigarh]=states;
console.log(Chennai);
console.log(Chandigarh);


module.exports = {states}

I have tried that code and i get undefined in  hackerrank??
Posted
Updated 20-Feb-23 20:50pm

Destructuring assignment - JavaScript | MDN[^]

Based on the vague details of the question, you're missing the "rest" pattern from your assignment:
JavaScript
let [Chennai, ...Chandigarh] = states;
But that still won't do anything, since the states array is empty.
 
Share this answer
 
var states = [['Tamilnadu'], ['Punjab', 'Haryana']]
let [Chennai, ...Chandigarh] = states;


module.exports = {states}
 
Share this answer
 
Comments
Richard Deeming 15-May-20 10:29am    
That won't work. The Chandigarh variable will be set to an array containing the required array, rather than the array itself.
Chandigarh === [ [ 'Punjab', 'Haryana' ] ] !== [ 'Punjab', 'Haryana' ]
var states = [['Tamilnadu'], ['Punjab', 'Haryana']];
const [Chennai, Chandigarh] = states;

module.exports = {states}

This would work!
 
Share this answer
 
v2
JavaScript
const states = [Chennai, Chandigarh] = [['Tamilnadu'], ['Punjab', 'Haryana']];

module.exports = {Chennai, Chandigarh}


Hi! this solutions works =)

Result in console:

> mocha

✓ returns respective state

✓ returns respective state

2 passing (9ms)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900