Home > front end >  How to use .map to get sting from array
How to use .map to get sting from array

Time:04-22

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?

CodePudding user response:

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) => (modified_roots.includes(roots) ? 'True Roots' : 'Modified Roots'))

console.log(trueRoots);

CodePudding user response:

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

CodePudding user response:

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)

  • Related