-1

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.

iceveda06
  • 601
  • 8
  • 21
  • 3
    You have two params, the first is an array of objects, the second is a string. Am I right that you are trying to loop through the objects in the array, and are trying to check if the second parameter exists in them? – Alex Szabo Nov 28 '16 at 22:59
  • Thats correct and if they do exist i want to print them out – iceveda06 Nov 28 '16 at 23:04
  • 1
    So... you're not comparing two arrays? Because that's what your title says. Might want to [edit] your question to update the title and first sentence. – Heretic Monkey Nov 28 '16 at 23:36
  • 1
    Also, it seems like what you're asking is essentially the same as this: [How do I check if an object has a property in JavaScript?](http://stackoverflow.com/q/135448/215552), just within a loop... – Heretic Monkey Nov 28 '16 at 23:37
  • *How do you compare two arrays* Which two arrays are you referring to? I only see one array. Do you mean array **elements**? *check to see if 2nd array exists on the first one* Which 2nd array? *Every time I do this* Show us the code you are having trouble with. –  Nov 29 '16 at 03:56

3 Answers3

0

If my assumption is correct, you could check if the given property exists in the array by looping through its items

var teleTubbies = [{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}];
var searchProperty = "sex";

function truthCheck(arrayToCheck, propertyToCheck) {
    arrayToCheck.forEach(function(item) {
    if(item.hasOwnProperty(propertyToCheck))
        console.log(item[propertyToCheck])
  });
}

truthCheck(teleTubbies, searchProperty);
Alex Szabo
  • 3,274
  • 2
  • 18
  • 30
0

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]));
}
PMV
  • 2,058
  • 1
  • 10
  • 15
0

Filter the input array of objects based on a condition that the specified property exists on an object (using the in operator).

function truthCheck(objects, p) {
  return objects.filter(e => p in e);
}