in method problems in javascript - javascript

I was trying to find as a dictionary (JS object) how many times each of the elements appears in some list. For example, the appearance of 1 in the list [1,1,2,2,1,3,4] is 3, because there are three ones in the list. In python I would implement this in the following way:
l = [1,1,2,2,1,3,4]
apr = dict()
for e in l:
if (e in apr.keys()):
apr[e] += 1
else:
apr[e] = 1
In javascript I decided to do
var arr = [1,1,2,2,1,3,4];
var vals = {};
for (let e of arr){
if (e in Object.keys(vals)){
vals[e] = vals[e] + 1;
}
else{
vals[e] = 1;
}
}
// vals = { '1': 2, '2': 1, '3': 1, '4': 1 }
which is obviously wrong. Then I tried if (Object.keys(vals).includes(e)){ instead, and it didn't work either. At the very end I implemented my own function my_in, and the progem worked:
function my_in(val,arr){
for (i = 0; i<=arr.length; i++){
if (val==arr[i]){
return true;
}
}
return false;
}
var arr = [1,1,2,2,1,3,4];
var vals = {};
for (let e of arr){
//if (Object.keys(vals).includes(e)){
// if (e in Object.keys(vals)){
if (my_in(e, Object.keys(vals))) {
vals[e] = vals[e] + 1;
}
else{
vals[e] = 1;
}
}
console.log(vals);
But I am still confused why did the first two tries didn't work. Is there anything I should be aware of when using in or includes()?

You need to use in operator with the object, not with an array this would check the indices.
For example by using an an array of keys
vals = { 1: 1 }
keys = Object(vals) // ['1']
if (1 in keys) performs
-> 1 in { 0: 1, length: 1 }, because there is only index zero with value one
-> false
var arr = [1, 1, 2, 2, 1, 3, 4];
var vals = {};
for (let e of arr) {
if (e in vals) { // check with object
vals[e] = vals[e] + 1;
} else {
vals[e] = 1;
}
}
console.log(vals);

The Object.keys(object) function returns an array of the string keys in the object.
When you do if (e in Object.keys(vals)) this would actually check the e element in the array returned from the Object.keys call. Which is not what you want.
You should simply check the presence of the e key in the vals object, if present increment by 1 else assign 0 to it:
var arr = [1,1,2,2,1,3,4];
var vals = {};
for (let e of arr){
vals[e] = (vals[e] || 0) + 1;
}
console.log(vals)
The issue with your code was, when you did Object.keys(vals) for the first iteration it returned an empty array [] as vals was an empty object {}. So e in Object.keys(vals) was false and it went to the else block. In the else block the vals[e] = 1 was executed.
In the next iteration when the check e in Object.keys(vals) happened it was evaluated to true as the array ["1"] was returned because vals is {1: 1}, same for the other elements so that is why you see {1: 2, 2: 1...}.

Related

Javascript - Adding multiple values to keys

I am trying to find the places of each letter in a sentence by using "dictionaries". The problem is I want to find all the places that each letter is and not only the last one. I am very new to JavaScript and couldn't figure out the way to do it.
function letters(stringArgument) {
stringArgument = stringArgument.replace(/ /g,'');
var dict = {};
for (var i=0; i < stringArgument.length; i++ )
if (!stringArgument[i] in dict){
dict[stringArgument[i]] = [];
}else{
dict[stringArgument[i]] = [i+1]
}
return dict
}
var a = letters('Lost time is never found again.');
console.log(a);
naturally gives this output:
{ L: [ 1 ], o: [ 17 ], s: [ 10 ], t: [ 5 ]...
but it should give this:
{ L: [ 1 ], o: [ 2, 17 ], s: [ 3, 10 ], t: [ 4, 5 ]...
Also each letter is saved to the dictionary at the same order they appear in the sentence, how can I order the letters alphabetically?
What you need is a function that gets the positions of a character in a given string.
Try this:
function findAllPositions(char, content) {
var result = [];
let index = content.indexOf(char);
while(index !== -1) {
result.push(index);
index = content.indexOf(char, index + 1);
}
return result;
}
findAllPositions('o', 'Lost time is never found again.'); // Result =  [1, 20]
Using this we can update the letter function as follows:
function letters(stringArgument) {
stringArgument = stringArgument.replace(/ /g, '');
var dict = {};
for (const char of stringArgument) {
dict[char] = findAllPositions(char, stringArgument)
}
return dict;
}
letters('is again.')
/*
{
"i": [0, 5],
"s": [1],
"a": [2, 4],
"g": [3],
"n": [6],
".": [7]
}
*/
You need to have
parantheses for the check
if (!(stringArgument[i] in dict)) {
create an array if the above is true
push the postion to the array
For getting a sorted output, you could take the entries of the object, apply a sorting by taking the key and show the result in order.
Object have an insertation oder for not positive 32 bit numbers (like indixes) or symbols. The index like numbers are sorted by value and appears first in the object.
function letters(stringArgument) {
stringArgument = stringArgument.replace(/ /g, '');
var dict = {};
for (var i = 0; i < stringArgument.length; i++) {
if (!(stringArgument[i] in dict)) {
dict[stringArgument[i]] = [];
}
dict[stringArgument[i]].push(i + 1);
}
return dict;
}
var a = letters('Lost time is never found again.');
Object
.entries(a)
.sort(([a], [b]) => a.localeCompare(b))
.forEach(([key, positions]) => console.log(key, ...positions));
console.log(a);
First, for any item, if it is not in an empty array:
var notInDict = !(stringArgument[i] in dict);
If not in dict, then initialize an empty array and push the item in it using
dict[stringArgument[i]].push(i + 1);
Try this.
function letters(stringArgument) {
stringArgument = stringArgument.replace(/ /g, "");
var dict = {};
for (var i = 0; i < stringArgument.length; i++) {
var notInDict = !(stringArgument[i] in dict);
if (notInDict) {
dict[stringArgument[i]] = [];
}
dict[stringArgument[i]].push(i + 1);
}
return dict;
}
var a = letters("Lost time is never found again.");
console.log(a);
you are assigning a new array at each iteration
dict[stringArgument[i]] = [i+1]
what you need to do is push the new position to existing array.
dict[stringArgument[i]].push(i+1)
also, remove the else block
function letters(stringArgument) {
stringArgument = stringArgument.toLowerCase().replace(/ /g,'');
var dict = {};
for (var i=0; i < stringArgument.length; i++ ){
if (!dict.hasOwnProperty(stringArgument[i])){
dict[stringArgument[i]] = [];
}
dict[stringArgument[i]].push(i+1);
}
//sorting
var letters = Object.keys(dict); //returns a array
letters.sort();
var sortedDic = {};
for(var i in letters) {
sortedDic[letters[i]] = dict[letters[i]];
}
return sortedDic;
}
var a = letters('Lost time is never found again.');
console.log(a);
for the first part you can also do that:
let sentence = 'Lost time is never found again.'
let tabLetters = [...sentence.replace(/ /g,'')].reduce((a,c,i)=>
{
if (!a[c]) a[c] = [i+1]
else a[c].push(i+1)
return a
},{})
document.write(JSON.stringify(tabLetters))

How to sort an array according to another array in javascript?

I count the words in a paragraph by frequency of occurrences now I need to sort them too for example [this : 2, is : 3, it : 1] to [is : 3, this : 2, it : 1]. I divided keys and values into two different arrays then I sorted an array of values now I want to sort an array of keys
console.log('app running');
function getFrequencyOfWord(word : string) {
let counting: any = {};
let wordSplit: any = word.split(' ');
wordSplit.forEach(function (word: any) {
if (counting[word]) {
counting[word]++;
}
else {
counting[word] = 1;
}
})
var arr1 = Object.keys(counting);
var arr2 = arr1.map((suboor)=> {
return counting[suboor];
});
for (var i : number = 0; i < arr2.length; i++) {
for (var j = 0; j < (arr2.length -i -1); j++) {
if (arr2[j] > arr2[j+1]) {
const lesser = arr2[j+1];
arr2[j+1] = arr2[j];
arr2[j] = lesser;
}
}
}
console.log(arr2);
console.log(arr1);
}```
You could try something like the following:
let word = "moo moo moo hello one two three one";
let wordSplit = word.split(' ');
var counting = [];
wordSplit.forEach(function (word) {
if (counting[word]) {
counting[word]++;
}
else {
counting[word] = 1;
}
})
console.log("Counting ...");console.log(counting);
function swap(json){
var ret = {};
for(var key in json){
let element = ret[json[key]] ;
//console.log("element");console.log(element);
if(element == undefined){
ret[json[key]] = element= [];
}
element.push(key);
//console.log("element");console.log(element);
}
return ret;
}
let result = swap(counting);
console.log("RESULT ...");console.log(result);
var finalResult = [];
for(var key in result){
finalResult = finalResult.concat(result[key]);
}
console.log("Final RESULT ...");console.log(finalResult);
Output
Word Count:
[moo: 3, hello: 1, one: 2, two: 1, three: 1]
Result:
{1: Array(3), 2: Array(1), 3: Array(1)}
1: (3) ["hello", "two", "three"]
2: ["one"]
3: ["moo"]
Final Result
0: "hello"
1: "two"
2: "three"
3: "one"
4: "moo"
Fiddle: https://jsfiddle.net/menelaosbgr/xe9u7mqk/33/
Update
The problem is that you actually have a map of object instead of an array. An array of objects would be something like [{is:3},{this:2},{it:1}] . It's not that difficult to do the conversion. However, I think it's better to have objects that are like this {word:X, count:x}. See below:
let word = "this this is is it is";
let wordSplit = word.split(' ');
var counting = [];
wordSplit.forEach(function (word) {
if (counting[word]) {
counting[word]++;
}
else {
counting[word] = 1;
}
})
console.log("Counting ...");console.log(counting);
function swap(json){
var ret = {};
for(var key in json){
let element = ret[json[key]] ;
//console.log("element");console.log(element);
if(element == undefined){
ret[json[key]] = element= [];
}
element.push({count:json[key], word:key});
//console.log("element");console.log(element);
}
return ret;
}
let result = swap(counting);
console.log("RESULT ...");console.log(result);
//Reverse it and make it into objects...
let reversedResult = Object.assign([], result ).reverse();
console.log("RESULT-REVERSED ...");console.log(reversedResult);
//Final Conatenated Array
var concatenatedArray = [];
for(var key in reversedResult){
concatenatedArray = concatenatedArray.concat(reversedResult[key]);
}
console.log("CONCATENATED-ARRAY ...");console.log(concatenatedArray);
Result:
0: {count: 3, word: "is"}
1: {count: 2, word: "this"}
2: {count: 1, word: "it"}
Fiddle: https://jsfiddle.net/menelaosbgr/xe9u7mqk/49/
This is not possible to sort array of keys according to array of values but you can do something to map right key to right value by checking if(arr[key] == arr[value]) and if key and value are equal then you can push that key value pair into new array.

I'm using labels in my code. But javascript keeps complaining 'label is not a statement.' [duplicate]

This question already has answers here:
Breaking out of an inner foreach loop
(2 answers)
Closed 3 years ago.
I'm using labels in my code. But javascript keeps complaining 'label is not a statement.'
function firstDuplicate(a) {
array1 = [];
b = a;
var val;
var valIndex;
var iCount = 0;
a.forEach(function(aLoop, aIndex) {
b.forEach(function(bLoop, bIndex) {
if (bLoop == aLoop) {
val = bLoop;
iCount = iCount++;
valIndex = bIndex;
} else { //I want to move evaluation to where I have label 'loop1'
break loop1;
}
});
obj = {
val: val,
index: valIndex,
count: iCount
};
array1.push(obj);
val = 0;
iCount = 0;
valIndex = 0;
loop1:
});
return array1;
}
console.log(firstDuplicate([2, 1, 3, 5, 3, 2]));
actual result is crashing; expecting js object be populated with 1) elements that occur > 1; index of the last occurence of the element; and count
You can't break out of a Array.forEach function.
You are using the post increment operator which won't work in this case. Here iCount = iCount++; will evaluate iCount as 0.
You also need to find the previous object inserted when there is a duplicate found in array1 and then increment its count. You can do this by using Array.find.
If a duplicate is found by comparing the aIndex and bIndex then we are pushing a new object into array1 with count as 1. If it is again encountered later we simply find the inserted object and increase the count and record the index in an array.
function firstDuplicate(a) {
array1 = [];
a.forEach(function(aLoop, aIndex) {
a.forEach(function(bLoop, bIndex) {
if (bIndex > aIndex && bLoop === aLoop) {
let dup = array1.find(o => o.val === bLoop);
if(!dup){
obj = {
val: bLoop,
index: [aIndex, bIndex],
count: 1
};
array1.push(obj);
}else{
dup.count = dup.count + 1;
dup.index = !dup.index.includes(bIndex) ? [bIndex].concat(dup.index) : dup.index;
}
}
});
});
return array1;
}
console.log(firstDuplicate([2, 1, 3, 5, 3, 2, 2, 3]));

Store count of integers in order using javascript

I have string like the following:
11222233344444445666
What I would like to do is output the number followed the times it was displayed:
112433475163
Question is, I want this to be efficient. I can store this in an object as the following:
1: { id: 1, displayed: 2},
2: { id: 2, displayed: 1},
3: { id: 3, displayed: 2},
etc.
I can access this object and increment displayed.
My issues is, there is no guarantee in the order. I would like to store the keys in the order they are in the string. How do I accomplish the importance of the order in the object?
This is a proposal for run length coding with an array which holds infomation about one charcter and the count of it:
{
"char": "1",
"count": 2
},
var string = "11222233344444445666",
array = function () {
var r = [], o = {};
string.split('').forEach(function (a, i, aa) {
if (a !== aa[i - 1]) {
o[a] = { char: a, count: 0 };
r.push(o[a]);
}
o[a].count++;
});
return r;
}(string);
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');
Quick solution with for loop:
var str = "7771122229933344444445666",
obj = {},
len = str.length,
val = null,
count_str = "",
key = "";
for (var i = 0; i < len; i++) {
val = str[i], key = 'k' + val;
if (!obj[key]) {
obj[key] = {'id': val, 'displayed': 1};
} else {
obj[key].displayed++;
}
}
for (var p in obj) {
count_str += obj[p]['id'] + obj[p]['displayed'];
}
console.log(count_str); // "7312249233475163"
because you have such a small set of distinct numbers, I seen no reason why you can't use a array (yeah it's not super ideal memorywise if you skip values and it becomes sparse, but for such a small subset it won't affect you enough to worry of it). Then you can use (number-1) as the index and increment that number as needed.
var counts = [];
var str = "11222233344444445666";
for(var i in str){
var index = parseInt(str[i])-1
counts[index] = (counts[index]||0)+1;
}
for(var i in counts){
var which = 1+parseInt(i);
var count = counts[i];
console.log("# of " + which +"'s: "+count);
}
https://jsfiddle.net/ga0fqpqn/
note: You shouldn't need the parseInt(i)... just +i should work but I think jsfiddle has a bug with it about it defaulting i to handle like a string.
You could store an additional array with the order of the numbers, which you only append to if the object doesn't yet contain the given number. Then once you're done counting, iterate through that array and output the number and the count from the lookup dictionary.
var chars = "1234576123452345".split("");
var order = [];
var hash = {};
chars.forEach(function(char) {
if (!hash[char]) {
hash[char] = 1;
order.push(char);
} else {
hash[char]++;
}
});
console.log(order.map(function(char) {
return char + hash[char];
}).join(""));
// "12233343537161"

Using jQuery to compare two arrays of Javascript objects

I have two arrays of JavaScript Objects that I'd like to compare to see if they are the same. The objects may not (and most likely will not) be in the same order in each array. Each array shouldn't have any more than 10 objects. I thought jQuery might have an elegant solution to this problem, but I wasn't able to find much online.
I know that a brute nested $.each(array, function(){}) solution could work, but is there any built in function that I'm not aware of?
Thanks.
There is an easy way...
$(arr1).not(arr2).length === 0 && $(arr2).not(arr1).length === 0
If the above returns true, both the arrays are same even if the elements are in different order.
NOTE: This works only for jquery versions < 3.0.0 when using JSON objects
I was also looking for this today and found:
http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256BFB0077DFFD
Don't know if that's a good solution though they do mention some performance considerations taken into account.
I like the idea of a jQuery helper method.
#David I'd rather see your compare method to work like:
jQuery.compare(a, b)
I doesn't make sense to me to be doing:
$(a).compare(b)
where a and b are arrays. Normally when you $(something) you'd be passing a selector string to work with DOM elements.
Also regarding sorting and 'caching' the sorted arrays:
I don't think sorting once at the start of the method instead of every time through the loop is 'caching'. The sort will still happen every time you call compare(b). That's just semantics, but...
for (var i = 0; t[i]; i++) { ...this loop finishes early if your t array contains a false value in it somewhere, so $([1, 2, 3, 4]).compare([1, false, 2, 3]) returns true!
More importantly the array sort() method sorts the array in place, so doing var b = t.sort() ...doesn't create a sorted copy of the original array, it sorts the original array and also assigns a reference to it in b. I don't think the compare method should have side-effects.
It seems what we need to do is to copy the arrays before working on them. The best answer I could find for how to do that in a jQuery way was by none other than John Resig here on SO! What is the most efficient way to deep clone an object in JavaScript? (see comments on his answer for the array version of the object cloning recipe)
In which case I think the code for it would be:
jQuery.extend({
compare: function (arrayA, arrayB) {
if (arrayA.length != arrayB.length) { return false; }
// sort modifies original array
// (which are passed by reference to our method!)
// so clone the arrays before sorting
var a = jQuery.extend(true, [], arrayA);
var b = jQuery.extend(true, [], arrayB);
a.sort();
b.sort();
for (var i = 0, l = a.length; i < l; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
});
var a = [1, 2, 3];
var b = [2, 3, 4];
var c = [3, 4, 2];
jQuery.compare(a, b);
// false
jQuery.compare(b, c);
// true
// c is still unsorted [3, 4, 2]
My approach was quite different - I flattened out both collections using JSON.stringify and used a normal string compare to check for equality.
I.e.
var arr1 = [
{Col: 'a', Val: 1},
{Col: 'b', Val: 2},
{Col: 'c', Val: 3}
];
var arr2 = [
{Col: 'x', Val: 24},
{Col: 'y', Val: 25},
{Col: 'z', Val: 26}
];
if(JSON.stringify(arr1) == JSON.stringify(arr2)){
alert('Collections are equal');
}else{
alert('Collections are not equal');
}
NB: Please note that his method assumes that both Collections are sorted in a similar fashion, if not, it would give you a false result!
Convert both array to string and compare
if (JSON.stringify(array1) == JSON.stringify(array2))
{
// your code here
}
I found this discussion because I needed a way to deep compare arrays and objects. Using the examples here, I came up with the following (broken up into 3 methods for clarity):
jQuery.extend({
compare : function (a,b) {
var obj_str = '[object Object]',
arr_str = '[object Array]',
a_type = Object.prototype.toString.apply(a),
b_type = Object.prototype.toString.apply(b);
if ( a_type !== b_type) { return false; }
else if (a_type === obj_str) {
return $.compareObject(a,b);
}
else if (a_type === arr_str) {
return $.compareArray(a,b);
}
return (a === b);
}
});
jQuery.extend({
compareArray: function (arrayA, arrayB) {
var a,b,i,a_type,b_type;
// References to each other?
if (arrayA === arrayB) { return true;}
if (arrayA.length != arrayB.length) { return false; }
// sort modifies original array
// (which are passed by reference to our method!)
// so clone the arrays before sorting
a = jQuery.extend(true, [], arrayA);
b = jQuery.extend(true, [], arrayB);
a.sort();
b.sort();
for (i = 0, l = a.length; i < l; i+=1) {
a_type = Object.prototype.toString.apply(a[i]);
b_type = Object.prototype.toString.apply(b[i]);
if (a_type !== b_type) {
return false;
}
if ($.compare(a[i],b[i]) === false) {
return false;
}
}
return true;
}
});
jQuery.extend({
compareObject : function(objA,objB) {
var i,a_type,b_type;
// Compare if they are references to each other
if (objA === objB) { return true;}
if (Object.keys(objA).length !== Object.keys(objB).length) { return false;}
for (i in objA) {
if (objA.hasOwnProperty(i)) {
if (typeof objB[i] === 'undefined') {
return false;
}
else {
a_type = Object.prototype.toString.apply(objA[i]);
b_type = Object.prototype.toString.apply(objB[i]);
if (a_type !== b_type) {
return false;
}
}
}
if ($.compare(objA[i],objB[i]) === false){
return false;
}
}
return true;
}
});
Testing
var a={a : {a : 1, b: 2}},
b={a : {a : 1, b: 2}},
c={a : {a : 1, b: 3}},
d=[1,2,3],
e=[2,1,3];
console.debug('a and b = ' + $.compare(a,b)); // a and b = true
console.debug('b and b = ' + $.compare(b,b)); // b and b = true
console.debug('b and c = ' + $.compare(b,c)); // b and c = false
console.debug('c and d = ' + $.compare(c,d)); // c and d = false
console.debug('d and e = ' + $.compare(d,e)); // d and e = true
In my case compared arrays contain only numbers and strings. This solution worked for me:
function are_arrs_equal(arr1, arr2){
return arr1.sort().toString() === arr2.sort().toString()
}
Let's test it!
arr1 = [1, 2, 3, 'nik']
arr2 = ['nik', 3, 1, 2]
arr3 = [1, 2, 5]
console.log (are_arrs_equal(arr1, arr2)) //true
console.log (are_arrs_equal(arr1, arr3)) //false
I don't think there's a good "jQuery " way to do this, but if you need efficiency, map one of the arrays by a certain key (one of the unique object fields), and then do comparison by looping through the other array and comparing against the map, or associative array, you just built.
If efficiency is not an issue, just compare every object in A to every object in B. As long as |A| and |B| are small, you should be okay.
Well, if you want to compare only the contents of arrays, there's a useful jQuery function $.inArray()
var arr = [11, "String #1", 14, "String #2"];
var arr_true = ["String #1", 14, "String #2", 11]; // contents are the same as arr
var arr_false = ["String #1", 14, "String #2", 16]; // contents differ
function test(arr_1, arr_2) {
var equal = arr_1.length == arr_2.length; // if array sizes mismatches, then we assume, that they are not equal
if (equal) {
$.each(arr_1, function (foo, val) {
if (!equal) return false;
if ($.inArray(val, arr_2) == -1) {
equal = false;
} else {
equal = true;
}
});
}
return equal;
}
alert('Array contents are the same? ' + test(arr, arr_true)); //- returns true
alert('Array contents are the same? ' + test(arr, arr_false)); //- returns false
Change array to string and compare
var arr = [1,2,3],
arr2 = [1,2,3];
console.log(arr.toString() === arr2.toString());
The nice one liner from Sudhakar R as jQuery global method.
/**
* Compare two arrays if they are equal even if they have different order.
*
* #link https://stackoverflow.com/a/7726509
*/
jQuery.extend({
/**
* #param {array} a
* First array to compare.
* #param {array} b
* Second array to compare.
* #return {boolean}
* True if both arrays are equal, otherwise false.
*/
arrayCompare: function (a, b) {
return $(a).not(b).get().length === 0 && $(b).not(a).get().length === 0;
}
});
I also found this when looking to do some array comparisons with jQuery. In my case I had strings which I knew to be arrays:
var needle = 'apple orange';
var haystack = 'kiwi orange banana apple plum';
But I cared if it was a complete match or only a partial match, so I used something like the following, based off of Sudhakar R's answer:
function compareStrings( needle, haystack ){
var needleArr = needle.split(" "),
haystackArr = haystack.split(" "),
compare = $(haystackArr).not(needleArr).get().length;
if( compare == 0 ){
return 'all';
} else if ( compare == haystackArr.length ) {
return 'none';
} else {
return 'partial';
}
}
If duplicates matter such that [1, 1, 2] should not be equal to [2, 1] but should equal [1, 2, 1], here is a reference counting solution:
const arrayContentsEqual = (arrayA, arrayB) => {
if (arrayA.length !== arrayB.length) {
return false}
const refCount = (function() {
const refCountMap = {};
const refCountFn = (elt, count) => {
refCountMap[elt] = (refCountMap[elt] || 0) + count}
refCountFn.isZero = () => {
for (let elt in refCountMap) {
if (refCountMap[elt] !== 0) {
return false}}
return true}
return refCountFn})()
arrayB.map(eltB => refCount(eltB, 1));
arrayA.map(eltA => refCount(eltA, -1));
return refCount.isZero()}
Here is the fiddle to play with.
var arr1 = [
{name: 'a', Val: 1},
{name: 'b', Val: 2},
{name: 'c', Val: 3}
];
var arr2 = [
{name: 'c', Val: 3},
{name: 'x', Val: 4},
{name: 'y', Val: 5},
{name: 'z', Val: 6}
];
var _isEqual = _.intersectionWith(arr1, arr2, _.isEqual);// common in both array
var _difference1 = _.differenceWith(arr1, arr2, _.isEqual);//difference from array1
var _difference2 = _.differenceWith(arr2, arr1, _.isEqual);//difference from array2
console.log(_isEqual);// common in both array
console.log(_difference1);//difference from array1
console.log(_difference2);//difference from array2
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>
Try this
function check(c,d){
var a = c, b = d,flg = 0;
if(a.length == b.length)
{
for(var i=0;i<a.length;i++)
a[i] != b[i] ? flg++ : 0;
}
else
{
flg = 1;
}
return flg = 0;
}

Categories