var array1 = [1, 2, 3, 4, 5, 6];
var array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
I have two arrays like above. Now I want to do the following in MVC 4 with jQuery.
If every elements of both arrays are equal then show a message/alert. e.g. "All records already existing."
If every elements of both the arrays are different then just add them all in a "VAR", e.g. var resultset = ....
(where 7,8,9 will stored)
If few elements common between two arrays then for the common elements show a message with element, e.g. "Record 1,2,3,4,5,6 are already exists" and add the different elements in "VAR", e.g. var resultset = ....
(where 7,8,9 will stored). Both the message and difference elements collection will perform at the same time.
Try this:
var array1 = [1, 2, 3, 4, 5, 6],
array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var common = $.grep(array1, function(element) {
return $.inArray(element, array2 ) !== -1;
});
console.log(common); // returns [1, 2, 3, 4, 5, 6];
var array3 = array2.filter(function(obj) { return array1.indexOf(obj) == -1; });
// returns [7,8,9];
Here is my version
function diff(arr1, arr2) {
var obj = {}, matched = [],
unmatched = [];
for (var i = 0, l = arr1.length; i < l; i++) {
obj[arr1[i]] = (obj[arr1[i]] || 0) + 1;
}
for (i = 0; i < arr2.length; i++) {
var val = arr2[i];
if (val in obj) {
matched.push(val);
} else {
unmatched.push(val);
}
}
// Here you can find how many times an element is repeating.
console.log(obj);
// Here you can find what are matching.
console.log(matched);
// Here you can check whether they are equal or not.
console.log('Both are equal ? :' +
matched.length === a.length);
// Here you can find what are different
console.log(unmatched);
}
If you do this kind of thing regularly, you may be interested in a Set object that makes this kind of stuff pretty easy:
var array1 = [1, 2, 3, 4, 5, 6];
var array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var common = new Set(array1).intersection(array2).keys();
The open source Set object (one simple source file) is here: https://github.com/jfriend00/Javascript-Set/blob/master/set.js
Along with the intersection()
method used here, it has all sorts of other set operations (union, difference, subset, superset, add, remove ...).
Working demo: http://jsfiddle.net/jfriend00/5SCdD/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With