I have two objects that has similar values except that one contains string values and the other integer values.

var ids = ["1", "5", "3"] var items = [ { id: 1 }, { id: 2 }, { id: 4 } ] var items2 = [ { id: 2 }, { id: 4 } ] 

What I'm trying to do is to check if any id key in the object items contains the same value from ids. So if ids contains "1" and that items has any id that also has 1, the function should return true

This is what I tried so far:

function checkIfValueExists(a, b) { if (a.some(i => i.includes(b.toString))) { console.log("value found") return true } else { console.log("value not found") return false } } checkIfValueExists(ids, items) // should console.log("value found") and returns true checkIfValueExists(ids, items2) // should return false 

How can I achieve this using JavaScript/ES6?

2

1 Answer

You can do that using some and includes. Apply the some() method on the on the items array and then convert the id of each item into string using toString and then use includes on ids.

var ids = ["1", "5", "3"];var items = [ { id: 1 }, { id: 2 }, { id: 4 }];var items2 = [ { id: 2 }, { id: 4 }]; const checkIfValueExists = (ids, items) => items.some(item => ids.includes(item.id.toString())) console.log(checkIfValueExists(ids, items)) // should console.log("value found") and returns true console.log(checkIfValueExists(ids, items2)) // should return false

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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