I am new to Javascript and encounter some problem. I am trying to compare the Array words to the Array days. If the word from Array words is not equal to day in Array days, the word will be pushed to name Array. I tried to use the script below, but it gives me different answer.
I am looking to get only the Name (Joe Smith) from the words array and will exclude the day if ever there is one.
function newFunction () {
var days = new Array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
var words = new Array("Joe", "Smith", "Tuesday");
var name = new Array();
var day = "";
for (x in words) {
for (y in days) {
if (words[x] == days[x]) {
day = days[x];
} else {
name.push(words[x]);
};
};
return name;
}
When I run the script, I got this result.
Result Joe,Joe,Joe,Joe,Joe,Joe,Joe,Smith,Smith,Smith,Smith,Smith,Smith,Smith,Tuesday,Tuesday,Tuesday
2 Answers 2
Your issue is that you are looking in the days array, but still adding it to names even though it is somewhere else in the array.
Here is a solution in simple JS:
function NewFunction (){
let days = new Array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
let words = new Array("Joe", "Smith", "Tuesday");
let name = new Array();
let day = "";
for(let i in words){
let found = false;
for(let j in days){
if(words[i] == days[j]){
day = days[j];
found = true;
}
}
if(!found){
name.push(words[i]);
}
}
return name;
}
Notice that I am looking for the word, but not adding it in the second loop, only setting a variable that it has been found and adding it outside
Note: There are much cleaner ways to do this with a little bit more advanced JS
Comments
You may use Array.prototype.filter() as suggested in the comment or fix the mistake you have in the inner loop. Change it from:
for (y in days) {
if (words[x] == days[x]) {
day = days[x];
} else {
name.push(words[x]);
}
}
to:
for (y in days) {
if (words[x] == days[y]) {
name.push(words[x]);
}
}
The snippet:
function newFunction() {
var days = new Array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
var words = new Array("Joe", "Smith", "Tuesday");
var name = new Array();
var day = "";
for (x in words) {
for (y in days) {
if (words[x] == days[y]) {
name.push(words[x]);
}
}
}
return name;
}
console.log(newFunction());
Comments
Explore related questions
See similar questions with these tags.
words.filter(v => !days.includes(v)), instead