Reputation: 27
this will probably be a very easy solution that I am missing, but hoping someone could help.
I am looping through an array and trying to figure out the length of it, and return different values depending on the length. Then I map through it and hopefully return the value depending on the amount. Could someone tell me what I am doing wrong?
Thanks!
EDIT Thank you all for your comments. What I intend to do with the switch statement result is determine a grid size depending on the getGridPercentages array value. So if it is '4' it would return '25% 25% 25% 25%'.
I am then using the value in a styled component using CSS grid's grid-template-columns:
const ContainerWrapper = styled.div `
display: grid;
grid-template-columns: ${op}; //Value of grid here
grid-gap: 10px;
`;
const getGridPercentages = [
{
Text: '1'
},
{
Text: '2'
},
{
Text: '3'
},
{
Text: '4'
}
]
let op = getGridPercentages.map(function(item) {
const getAmount = item.Text;
switch(getAmount) {
case '1':
return '100%'
case '2':
return '50% 50%'
case '3':
return '33% 33% 33%'
case '4':
return '25% 25% 25% 25%'
default:
return 1
}
});
Upvotes: 0
Views: 432
Reputation: 37755
You should make these changes
const getGridPercentages = [
{
Text: '1'
},
{
Text: '2'
},
{
Text: '3'
},
{
Text: '4'
}
]
let op = getGridPercentages.map(function(item) {
const getAmount = item.Text;
switch(getAmount) {
case '1':
return '100%'
case '2':
return '50% 50%'
case '3':
return '33% 33% 33%'
case '4':
return '25% 25% 25% 25%'
default:
return 1
}
});
console.log(op);
Update: As you asked in comments you want based on number of elements which is in complete contrary of what question is saying.
const getGridPercentages = [
{
Text: '1'
},
{
Text: '2'
},
{
Text: '3'
},
{
Text: '4'
}
]
function getGridSize(arr){
switch(arr.length) {
case 1:
return '100%'
case 2:
return '50% 50%'
case 3:
return '33% 33% 33%'
case 4:
return '25% 25% 25% 25%'
default:
return 1
}
}
console.log(getGridSize(getGridPercentages))
Upvotes: 2
Reputation: 3064
Two problems:
One, you don't need a break
statement after a return
. That's what's triggering the error in the console.
Two, you are switching on the length of each Text
field. Text's length is always one. Therefore any other branches in your switch statement are also unreachable code.
Upvotes: 0
Reputation: 1111
You are using switch statement and when the condition match you are returning a value so there is no need for using break; keyword after return. Your switch statement should looks like:
switch(getAmount) {
case 1:
return '100%'
case 2:
return '50% 50%'
case 3:
return '33% 33% 33%'
case 4:
return '25% 25% 25% 25%'
default:
return 1
}
EDIT: and also you are getting the length of every Text string which will be in your case every time 1.
Upvotes: -1