bla
bla

Reputation: 1055

Include element in array if is not present in other array

I have this array:

let idsClass = [1,2]

and i have this other array:

let idsQuiz = [{id: 1}]

I need to know the id numbers that have in idsClass that is missing in idsQuiz.

So, i need an new array containing this elements, for this example, this is the correct output:

[2]

I tryed something like:

 idsClass.forEach(item => { if (!idsQuizz.includes({id:item})) { console.log('dont find this: ' + item) } })

But my console is printing the two elements

Upvotes: 0

Views: 1451

Answers (3)

Mike Reddington
Mike Reddington

Reputation: 372

basic solution

let idsClass = [1,2,2,4,5,6];
let idsQuiz = [1,4];
for(let i=0;i<idsClass.length;i++){
    let j=0;
    for(;j<idsQuiz.length;j++){
        if(idsClass[i] === idsQuiz[j]){
            break;
        }
    }
    if(j === idsQuiz.length) {
        idsQuiz.push(idsClass[i]);
    }
}
console.log(idsQuiz);

solution using inbuilt methods

let idsClass = [1,2,2,4,5,6];
let idsQuiz = [1,4];

// Adds all elements of idsClass into idsQuiz. may contain duplicates
idsQuiz.push(...idsClass);

//Removes duplicates from idsQuiz
idsQuiz = idsQuiz.filter((val,index,self) => self.indexOf(val) === index);
console.log(idsQuiz);

your code adds element into idsQuiz whenever an element in idsClass doesn't match with an element in idsQuiz. Instead, iterate through whole idsQuiz list and then add if it doesn't exist for each idsClass element.

idsClass = [1,2,3]
idsQuiz = [1]

i = 0, j=0 (no element is added in idsQuiz)
i=1, j=0 (2 is added in idsQuiz)
i=1, j=1 (no element is added in idsQuiz)
i=2, j=0 (3 is added in idsQuiz)
i=2, j=1 (3 is added in idsQuiz)
i=2, j=2 (no element is added in idsQuiz)
i=2, j=3 (no element is added in idsQuiz)

Upvotes: 2

Rise
Rise

Reputation: 1601

Try to use filter built-in function to check existence.

let idsClass = [1,2];


let idsQuiz = [{id: 1}];

idsClass.forEach(item => {
  if (idsQuiz.filter(e => e.id === item).length === 0) {
    idsQuiz.push({id: item});
  }
});

console.log(idsQuiz); // output is [{"id": 1}, {"id": 2}]

Upvotes: 3

Klaycon
Klaycon

Reputation: 11080

There's probably a more efficient method, but I think this way is easy to understand:

let idsClass = [1,2,3,4,5,6];
let idsQuiz = [{id: 1},{id: 4}];

let result = idsClass.filter(n => !idsQuiz.some(o => o.id == n));

console.log(result);

Simply use a filter() on the idsClass. filter will return a new array with only the elements that pass the inner function. In this case, it only returns elements that aren't in the idsQuiz.

Upvotes: 1

Related Questions