showing results for - "javascript check if two arrays of objects have same elements"
Emily
19 Feb 2018
1var isEqual = function (value, other) {
2
3	// Get the value type
4	var type = Object.prototype.toString.call(value);
5
6	// If the two objects are not the same type, return false
7	if (type !== Object.prototype.toString.call(other)) return false;
8
9	// If items are not an object or array, return false
10	if (['[object Array]', '[object Object]'].indexOf(type) < 0) return false;
11
12	// Compare the length of the length of the two items
13	var valueLen = type === '[object Array]' ? value.length : Object.keys(value).length;
14	var otherLen = type === '[object Array]' ? other.length : Object.keys(other).length;
15	if (valueLen !== otherLen) return false;
16
17	// Compare two items
18	var compare = function (item1, item2) {
19
20		// Get the object type
21		var itemType = Object.prototype.toString.call(item1);
22
23		// If an object or array, compare recursively
24		if (['[object Array]', '[object Object]'].indexOf(itemType) >= 0) {
25			if (!isEqual(item1, item2)) return false;
26		}
27
28		// Otherwise, do a simple comparison
29		else {
30
31			// If the two items are not the same type, return false
32			if (itemType !== Object.prototype.toString.call(item2)) return false;
33
34			// Else if it's a function, convert to a string and compare
35			// Otherwise, just compare
36			if (itemType === '[object Function]') {
37				if (item1.toString() !== item2.toString()) return false;
38			} else {
39				if (item1 !== item2) return false;
40			}
41
42		}
43	};
44
45	// Compare properties
46	if (type === '[object Array]') {
47		for (var i = 0; i < valueLen; i++) {
48			if (compare(value[i], other[i]) === false) return false;
49		}
50	} else {
51		for (var key in value) {
52			if (value.hasOwnProperty(key)) {
53				if (compare(value[key], other[key]) === false) return false;
54			}
55		}
56	}
57
58	// If nothing failed, return true
59	return true;
60
61};
62