1

I try make a reject function find a missing values in a array:

var store = [0,1,2,3,4,5,6,7,8,15,16,18,20,21];
var fullArray= [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21];
function reject(array, iteratorFunction) {
    return array.filter(function(element) {
        return !iteratorFunction(element)});
}
var missingValues = reject(fullArray, function(number){
  return store.find(function(item){return number === item});
}); 
console.log(missingValues);

but my result shows:

[0,9,10,11,12,13,14,17,19] 

showing me a 0 in the first value. why this occurs and how to fix it?

2 Answers 2

2

store.find returns the element it finds. If that’s 0, your iteratorFunction will return 0, and !0 is true because 0 is falsy.

A correct presence check using Array#includes is even more concise, though:

var missingValues = reject(fullArray, function (number) {
  return store.includes(number);
});
Sign up to request clarification or add additional context in comments.

Comments

0

You may also do as follows in a more concise way;

var store     = [0,1,2,3,4,5,6,7,8,15,16,18,20,21],
    fullArray = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21],
    result    = fullArray.filter(n => !store.includes(n));
console.log(result);

However this would run in O(n.m) so a more efficient way would be;

var store     = [0,1,2,3,4,5,6,7,8,15,16,18,20,21],
    fullArray = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21],
    result    = fullArray.reduce((t,m) => (!t[m] && t.r.push(m),t), store.reduce((h,n) => (h[n] = true,h),{r:[]})).r;
console.log(result);

which runs in O(n + m)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.