Kiralin
Kiralin

Reputation: 23

How to filter out specific words in an Array with Javascript

Okay so, I'm new to Javascript and im just trying to get the hang of loops and how to use them. So I came up with an exercise:

this is my current code :

let words = ['mango','desk','phone','banana','airpods', 6 ,'mouse','strawberry',9,'raspberry', 10];

let wordsArrayLength = words.length;

for (let wordLoop = 0; wordLoop < wordsArrayLength; wordLoop++ ) {

}

So I thought I would do a .filter() and then call out those names, and replace them with the word Fruit but I'm just kinda stuck now and I don't know how to go on from here... I couldnt find anything online that helped me with this, so maybe I didn't really make a good exercise for myself?

Also if anyone has any tips on what to practise with, with Javascript then let me know. Im thinking of making a puzzle/quiz next. I just wanted to know if there was a solution for what im trying to make now or if I just move on.

Upvotes: 1

Views: 7564

Answers (3)

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You can create a new array called fruits that will have all the fruits item. With that you can loop over to the words array and check if the item is fruit or not using fruits.indexOf(). If it is simply replace that word with Fruit:

let fruits = ['mango','banana','strawberry','raspberry'];
  let words = ['mango','desk','phone','banana','airpods', 6 ,'mouse','strawberry',9,'raspberry', 10];

words.forEach((word, index) => {
  if(fruits.indexOf(word) !== -1){
     words[index] = 'Fruit';
  }
});
console.log(words);

Upvotes: 1

fransyozef
fransyozef

Reputation: 574

You could do this with map (https://www.w3schools.com/jsref/jsref_map.asp)

So what the map function does is loop through every item in the array and pass it to a function so you can transform that value

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370849

You don't want to filter out words - you want to create an array that's one-to-one with the original array, only with the fruit words replaced. Use .map instead.

You can also put the predefined fruit words into Set to reduce runtime complexity:

const fruits = new Set(['mango', 'banana', 'strawberry', 'raspberry']);
const input = ['mango','desk','phone','banana','airpods', 6 ,'mouse','strawberry',9,'raspberry', 10];
const mapped = input.map(val => fruits.has(val) ? 'fruit' : val);
console.log(mapped);

Or, using only array methods, you would test to see if the fruits array includes the value:

const fruits = ['mango', 'banana', 'strawberry', 'raspberry'];
const input = ['mango','desk','phone','banana','airpods', 6 ,'mouse','strawberry',9,'raspberry', 10];
const mapped = input.map(val => fruits.includes(val) ? 'fruit' : val);
console.log(mapped);

Upvotes: 2

Related Questions