I’m sure this is simple, but I can’t get it! Here is the flow of a program:
- receives a new array (newArray)
- uses filter to check each item of the array, make sure it doesn’t exist in the old array (oldArray)
- adds the new items that pass the filter into the old array
The problem is, it doesn’t seem to work if 0 is one of the values that needs to be included. I don’t see why not, though…
const oldArray = [some stuff];
const stuffToBeAdded = newArray.filter((item) => {
if (oldArray.indexOf(item) === -1) {
return item }
else {
return false;
}
By the way, this is in React, although it doesn’t work in the console, either (I “translated” it for this post). I’ll add the React code below.
updateAnswers = (answer) => {
let recForm = "";
if (answer) {
let temp = quizData[this.state.currentQuestion].form; //form numbers to add to state
console.log(temp)
recForm = temp.filter((item) => {
if (this.state.recForms.indexOf(item) === -1) { //only add items that don't already exist in the array
return item;
} else {
return false;
}
}
)
}
console.log(recForm);
this.setState((prevState) => ({
answers: prevState.answers + answer,
currentQuestion: prevState.currentQuestion + 1,
recForms: [...prevState.recForms, ...recForm] //adds any new items (might be in array) to the old array
}
));
}