Tag:html5htmljavascriptphp
Article From:https://segmentfault.com/q/1010000012141980
Question:

a[1,2,3,5,6]And how b[1,2,4,6] can get a lot of a and less a

Answer 0:

A has B No:

a.filter(item => !b.includes(item))

B has a No:

b.filter(item => !a.includes(item))

Answer 1:

Through your analysis of the problem, the multiple parts of the array A and the less part of the a can be understood as the difference set of two arrays, which can be implemented in two ways:

 Array.prototype.minus = function (arr) {
    var result = new Array();
    var obj = {};
    for (var i = 0; i < arr.length; i++) {
        obj[arr[i]] = 1;
    }
    for (var j = 0; j < this.length; j++) {
        if (!obj[this[j]])
        {
            obj[this[j]] = 1;
            result.push(this[j]);
        }
    }
    return result;
};
let a = [1, 2, 3, 5, 6];
let b = [1, 2, 4, 6];
// Get the part of the array aConsole.log (a.minus (b));/ / get part of the array aConsole.log (b.minus (a));

If you use ES6 syntax in your project, use the upstairs ES6 syntax:

let a = [1, 2, 3, 5, 6];
let b = [1, 2, 4, 6];
// Get the part of the array aA.filter (item =>! B.includes (item))/ / get part of the array aB.filter (item =>! A.includes (item)))

I hope to be of help to you.

Answer 2:

Try this array_diff and its related functions, array_diff_assoc and so on.

Answer 3:

phpYou can just use array_diff

aFew:

array_diff($b, $a);

In turn, there are more a:

array_diff($a, $b);

Return an array.

https://secure.php.net/manual…

Answer 4:
  • The two arrays are respectively recycled for key value inversion, that is, a becomes array (“1” =&gt, “”, “2” =&gt “,”… “), B becomes array (” 1 “=&gt,” “,” 4 “=&gt,” “).
  • Cycle a again, check whether each key key of a is isset (b[key]), if false is returned, it is more than a, if true is returned, unset (b[key]).
  • Cycle B again, check whether each key key of B is isset (a[key]), and if false is returned, it is less a.

The time complexity of the algorithm is O (n)

Answer 5:

The results can be obtained quickly by using Math.max and Math.min methods.

Answer 6:

phpComparison is simple, JS comparison is more troublesome, it is better to write a function to judge.

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *