Search code examples
javascriptarraysfunctionobjectboolean

Function to covert boolean from false to true (with condition) within an object array JavaScript


I am working on a task for the coding bootcamp I am enrolled on, this task is to have an array with 10 words and all with a boolean value, if the words contain 6 or more letters they should be pushed to a new array and the boolean should be converted as part of a callback function.

I have set all the values to false, and I am trying to switch them to true.

I have successfully pushed all the 6+ letter words into an array, but I cannot seem to convert the boolean value.

You can see in my code here what I have tried, I have made comments within the function.

Any pointers would be appreciated.

 let words = [
     {name:"Lion", sixOrMore: false},
     {name: "Jaguar", sixOrMore: false},
     {name: "Cheetah", sixOrMore: false},
     {name: "Tiger", sixOrMore: false},
     {name: "Leopard", sixOrMore: false},
     {name: "Bobcat", sixOrMore: false},
     {name: "Puma", sixOrMore: false},
     {name: "Ocelot", sixOrMore: false},
     {name: "Lynx", sixOrMore: false},
     {name: "Caracal", sixOrMore: false},
 ]

let sixLetterWords = []

let names = words.map(item => item.name);

const myFilterFunction = () => {

     for (i=0; i < names.length; i++){
        if (names[i].length >= 6) {
            sixLetterWords.push(words[i])
        }
    } 
} 

let sixLetterNames = sixLetterWords.map(item => item.name);

const trueVal = () => {
    for (j=0; j < sixLetterNames.length; j++){
        if (sixLetterNames[j].length >= 6) {
            //words[j] = JSON.parse(JSON.stringify(words).replaceAll("false","true"));
            //return words[j].forEach((item) => item.sixOrMore = true);
            //words[j].sixOrMore = true
        }
    }
}

myFilterFunction(words)
console.log(JSON.stringify(sixLetterWords))

trueVal(words)
console.log(JSON.stringify(words))

Solution

  • There's no need for the names array. Just loop over words and do everything you want.

    words.forEach(word => {
        if (word.name.length >= 6) {
            word.sixOrMore = true;
            sixLetterWords.push(word);
        }
    });
    

    You can also do it with filter(). While filter callback functions normally just test the value to determine whether it should be in the result, it can also modify the object while it's running.

    let sixLetterWords = words.filter(word => 
        if (word.name.length >= 6) {
            word.sixOrMore = true;
            return true;
        }
        return false;
    });