LearningToCode LearningToCode - 8 days ago 6
Javascript Question

compare an array that has an object

How do you compare two arrays, especially if the first array is an object with multiple parameters?

truthCheck([
{ "user": "Tinky-Winky", "sex": "male" },
{ "user": "Dipsy", "sex": "male" },
{ "user": "Laa-Laa", "sex": "female" },
{ "user": "Po", "sex": "female" }
], "sex");


I thought of looping through first array, then check to see if 2nd array exists on the first one. Output the answer. Every time I do this, I get an empty array or in some cases just number 0, 1, 2, 3.

PMV PMV
Answer

I'll add my implementation into the mix - like the others it uses array.forEach but I think it's logically simpler to do the filtering (checking for the existence of "sex") in .filter() and then do .forEach() on the result. My implementation is ES6, but you can use the older anonymous function syntax, too.

function truthCheck(arrayToCheck, propertyToCheck) {
    arrayToCheck.filter( elem => elem.hasOwnProperty(propertyToCheck)).forEach(elem => console.log(elem[propertyToCheck]));
}