0

I would like to have a function in javascript (jQuery if possible) that will allow me to pass an array of ids into a function, and check if each value is found in another array to return TRUE.

e.g

var ids1 = [1, 6, 9, 11, 20];
var ids2 = [5, 6, 9, 11];

function check_array(ids)
{
    var search = [1, 6, 9, 11, 20];
    // do some checking here

    // if all ids are matched up return TRUE; 

    // otherwise return FALSE;
}

In this instance - the first var ids1 would return TRUE, while the second var ids2 would return FALSE.

Can anyone suggest the simplest/cleanest method for this?

Zabs
  • 13,852
  • 45
  • 173
  • 297
  • 3
    Have you tried anything yourself? – Aleks G Jun 25 '13 at 12:53
  • I didn't try myself purely as I thought that they might be a javascript function that already does this that I am not aware e.g. array_diff() in PHP would allow me to do this, I wondered if javascript had a similar function – Zabs Jun 25 '13 at 12:59

2 Answers2

2
function check_array(ids1, ids2) {
    return $(ids1).not(ids2).get().length === 0;
}

var ids1 = [1, 6, 9, 11, 20];
var ids2 = [5, 6, 9, 11];
console.log(check_array(ids1, ids2)); // false
console.log(check_array(ids2, ids1)); // false
var search = [1, 6, 9, 11, 20];
console.log(check_array(search, ids2)); // false
console.log(check_array(search, ids1)); // true

Although the generic version above is enough, here's one that's exactly what you ask:

function check_array(ids) {
    var search = [1, 6, 9, 11, 20];
    return $(search).not(ids).get().length === 0;
}
var ids1 = [1, 6, 9, 11, 20];
var ids2 = [5, 6, 9, 11];
console.log(check_array(ids1)); // true
console.log(check_array(ids2)); // false
acdcjunior
  • 132,397
  • 37
  • 331
  • 304
1

If you only have numeric IDs, then this is possibly the simplest way.

[1,2,3].toString() === [1,2,3].toString() //=> true

If you want to determine if all the IDs in array A exist in array B (but array B may have others), try [].every

Graham
  • 6,484
  • 2
  • 35
  • 39