Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

jquery - How to check whether multiple values exist within an Javascript array

So, I'm using Jquery and have two arrays both with multiple values and I want to check whether all the values in the first array exist in the second.

For instance, example 1...

Array A contains the following values

34, 78, 89

Array B contains the following values

78, 67, 34, 99, 56, 89

This would return true

...example 2:

Array A contains the following values

34, 78, 89

Array B contains the following values

78, 67, 99, 56, 89

This would return false

...example 3:

Array A contains the following values

34, 78, 89

Array B contains the following values

78, 89

This would return false

So far I have tried to solve this by:

  1. Extending Jquery with a custom 'compare' method to compare the two arrays. Problem is this only returns true when the arrays are identical and as you can see from example 1 I want it to return true even if they aren't identical but at least contain the value
  2. using Jquerys .inArray function, but this only checks for one value in an array, not multiple.

Any light that anyone could throw on this would be great.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Native JavaScript solution

var success = array_a.every(function(val) {
    return array_b.indexOf(val) !== -1;
});

You'll need compatibility patches for every and indexOf if you're supporting older browsers, including IE8.


Full jQuery solution

var success = $.grep(array_a, function(v,i) {
    return $.inArray(v, array_b) !== -1;
}).length === array_a.length;

Uses $.grep with $.inArray.


ES2015 Solution

The native solution above can be shortened using ES2015's arrow function syntax and its .includes() method:

let success = array_a.every((val) => array_b.includes(val))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...