1

I have an array of values, for example:

let values = [1, 2, 3, 4, 5];

And I have another array, containing objects, for example:

let objects = [{name: 'Dennis', value: 2}, {name: 'Charlie', value: 4}];

I would like to produce an array that only contains values that aren't present in the value property of my objects. So from the examples above, I would return an array of [1, 3, 5]

What I've got at the moment is:

let missingValues = [];
for (let i = 0; i < values.length; i++) {
    if (!objects.filter(obj => obj.value === values[i]) {
        missingValues.push(values[i]);
    }
}

This works, but feels slightly messy, is there a more efficient way to do this?

0

2 Answers 2

3

You could filter the values with a look up in the objects array.

var values = [1, 2, 3, 4, 5],
    objects = [{ name: 'Dennis', value: 2 }, { name: 'Charlie', value: 4 }],
    result = values.filter(v => !objects.find(({ value }) => value === v));
    
console.log(result);

Sign up to request clarification or add additional context in comments.

2 Comments

This works well thanks. Out of curiosity, say values was also an array of objects like objects. Would you simply alter the .find to the property you're interested in and then add a map on the end? Or go for a completely different approach?
then i would use !objects.find(({ value }) => value.includes(v)).
2

...is there a more efficient way to do this?

I assume you really mean "efficient" (as opposed to "concise").

Yes, you can build an object or Set containing the values from the second array, and then use that to filter instead:

let values = [1, 2, 3, 4, 5];

let objects = [{name: 'Dennis', value: 2}, {name: 'Charlie', value: 4}];

let valueSet = new Set();
for (const obj of objects) {
    valueSet.add(obj.value);
}

let missingValues = values.filter(value => !valueSet.has(value));

console.log(missingValues);

(You can also use an object for the same thing, if you prefer. let valueSet = Object.create(null); then valueSet[value] = true and !valueSet[value].)

This is only worth doing if the product of the arrays is quite large (hundreds of thousands of entries) or you're doing this a lot.

1 Comment

I don't think I'd ever be dealing with much more than 100-150 entires and it won't be executed that frequently. But thanks for this answer, interesting to see a different approach

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.