-3

Hi very new to javascript but how do I filter out words that occur once in the array please?

If my code would say

function uniqueWord(word) {
 
}

const result = uniqueWord([cat, dog, cat, cow])
console.log(result)
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Bjork
  • 57
  • 7
  • 1
    [How do I ask and answer homework questions?](https://meta.stackoverflow.com/q/334822) and [Open letter to students with homework problems](https://softwareengineering.meta.stackexchange.com/q/6166) – VLAZ May 08 '21 at 14:07
  • When I learn a new language, I read through the whole documentation. Not to learn, but so I can remember if I read about it before. Here's a link to get you started: https://developer.mozilla.org/en-US/docs/Web/JavaScript If you had done that, then you would have stumbled across this page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter Good luck! – Rickard Elimää May 08 '21 at 14:15

3 Answers3

1
const numbers = [2,3,4,4,2,3,3,4,4,5,5,6,6,7,5,32,3,4,5]

console.log([...new Set(numbers)])
Khant
  • 958
  • 5
  • 20
0

I am not exactly sure what you are asking, but if you want to have an array with all the occurrences only once. Here is what you can do

function uniqueWord(word) {
   let arr = [];
   word.forEach(element => {
     if(!arr.includes(element)){
        arr.push(element);
     }
   });
   return arr;
}

You can get more ways to acheive similar from here

Utkarsh
  • 635
  • 7
  • 14
0

I am not sure what you mean filter out words that occur once. Do you want to delete the words that only occur once? Or delete repetitive words in the array? If it's the latter then here is the code to do it:

function uniqueWord(arr){
    let aux = [];
    for(var i=0; i<arr.length; i++){
        if(!isContainedInArray(arr[i], aux))
            aux.push(arr[i]);
    }
    return aux;
}

function isContainedInArray(word, array){
    for(var i=0; i<array.length; i++){
        if(array[i] == word)
            return true;
    }
    return false;
}

also you can't write cat, dog like this const result = uniqueWord([cat, dog, cat, cow]) Javascript will assume that there is a variable named cat and it will try to find it and it will fail and return an error.
You should write it like this: const result = uniqueWord(["cat", "dog", "cat", "cow"]), as as string.
The obove code will return ["cat", "dog", "cow"]

Kamel Yehya
  • 33
  • 1
  • 8