'How to use .map to get sting from array
This is my first question because I'm just new to coding.
I want to use .map to get strings from an array.
let root_vegetables = ['potato', 'taro', 'sweet potato', 'carrot']
let trueRoots = root_vegetables.map((roots) => {
if (roots == 'carrot' && 'sweet potato') {
return 'True Roots';
}
return 'Modified Roots';
})
console.log(trueRoots);
so my expected answer is.
['Modified Roots', 'Modified Roots', 'True Roots', 'True Roots']
Is there Anyways to do this?
Solution 1:[1]
Is this what you were asking.
let root_vegetables = ['potato', 'taro', 'sweet potato', 'carrot']
let trueRoots = root_vegetables.map((roots) => {
if (roots == 'carrot' || roots =='sweet potato') {
return 'True Roots';
}
return 'Modified Roots';
})
console.log(trueRoots);
Solution 2:[2]
Keeping your code almost same, you can also do it like this:
let root_vegetables = ['potato', 'taro', 'sweet potato', 'carrot']
var roots = [];
for (var i = 0; i < root_vegetables.length; i++) {
roots[i] = 'Modified Roots';
if (root_vegetables[i] == 'carrot' || root_vegetables[i] == 'sweet potato') {
roots[i] = 'True Roots'
}
}
console.log(roots)
Solution 3:[3]
Looks like your if statement condition is incorrect. You're doing (roots == 'carrot' && 'sweet potato'), which won't work because you need to have another condition after the AND operation(&&) and not a value as that'll just return true (The statement after the AND, not the if condition)
So you can change roots == 'carrot' && 'sweet potato' to roots == 'carrot' || roots == 'sweet potato'. Note that we conditon got changed from an AND to an OR condition.
But you can also do:
// We use the const keyword instead of let if we don't change the value
// We use true_roots array to do the checking
const true_roots = ['carrot', 'sweet potato']
const root_vegetables = ['potato', 'taro', 'sweet potato', 'carrot']
// We loop through the root_vegetables array and for each value
// we check if its in the true_roots array using the .includes method
// If its included, we return 'True Roots'
// else return 'Modified Roots'
// The code inside the map function is just shorthand/syntactical sugar
const trueRoots = root_vegetables.map((roots) => (true_roots.includes(roots) ? 'True Roots' : 'Modified Roots'))
console.log(trueRoots);
Solution 4:[4]
You can simply achieve this with a single line of code by using || operator instead of && along with the ternary operator.
let root_vegetables = ['potato', 'taro', 'sweet potato', 'carrot']
let trueRoots = root_vegetables.map(roots => (roots === 'carrot' || roots === 'sweet potato') ? 'True Roots' : 'Modified Roots')
console.log(trueRoots);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kb019 |
| Solution 2 | |
| Solution 3 | |
| Solution 4 | Rohìt JÃndal |
