0

I have an array of objects A obtained from JSON data which is like:

[Object { field1="2381", field2="1233", field3="46.44852", more...},
Object { field1="2381", field2="1774", field3="45.70752833333334", more...}]

And I have another array B like

["2381", "1187"]

Is there a way to check if values of this array B exists in array A?

I tried with something like

A.map((B[0], B[1]), function(element) {
    if (B[0] == element.field1 && B[1] == element.field2) 
        return true; 
    else 
        return false; 
});

but it didn't worked well...

Any trick?

1

3 Answers 3

1

To see if there's at least one item in A that matches B.

A.some(function(value) {
    return value.field1 == B[0] && value.field2 == B[1];
});
Sign up to request clarification or add additional context in comments.

Comments

0

You can use a nested for loop. Something along the lines of:

 var checker; //number to hold the current value
for(x=0;x<arrayA.length; x++) //loop through the first array
{
  checker = arrayA[x]; store the number in each element in the variable
 for(y=array.Indexof(arrayA, checker);y<arrayB.length; y++) /*don't start from the very first index of the array but rather from the last place where arrayA was*/
  {
   if (arrayB[y] == checker)
     {
   Alert(checker + " is the same");
 }//closes if
}//closes for
}//closes outer for loop

Obviously you would substitue the alert for your particular needs. My syntax may be a little off but you get the gist. Hope this helps...

Comments

0

You could use a function like this one :

function check(arr, fn) {
    var i = 0, l = arr.length;
    for (; i < l; i++) {
        if (fn(arr[i])) return true;
    }
    return false;
}

Usage :

var A, B;

A = [
    { field1: 1, field2: 2 },
    { field1: 1, field2: 3 },
    { field1: 2, field2: 3 }
];

B = [1, 3];
check(A, function (item) {
    return item.field1 === B[0] && item.field2 === B[1];
}); // true

B = [2, 1];
check(A, function (item) {
    return item.field1 === B[0] && item.field2 === B[1];
}); // false

1 Comment

You mean arr is my array A and fn is array B ?

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.