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)
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)
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)])
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
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"]