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?
21 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