Compare Two Array in Javascript/AngularJS - javascript

I want to check two array values are same or not. I am using a form with checkboxes. need show any change in checkbox array or not?. can anyone help me. Two arrays Like this.
array1 = ['1','2','3']; //previous checklist
array2 = ['3','2','1']; //new checklist

Here is a snippet that compares two arrays.
var array1 = [1,2,3];
var array2 = [1,2,3];
var result = array1.length == array2.length && array1.every(function(element, index) {
return element === array2[index];
});
alert(result);
however 1,2,3 in one array is not equal with 3,2,1 in another. You didn't mentioned about to check the array elements or just the array !
In Case you need to compare two arrays with different positions, try this
var array1=[1,2,3,4]
var array2=[1,4,3,2]
var result = array1.length==array2.length && array1.every(function(v,i) { return ($.inArray(v,array2) != -1)})
console.log(result)

I got this:
let arr = ['1', '2', '3'];
let arr2 = ['3', '1', '2'];
let finalResult = arr.length === arr2.length;
arr.forEach(function (item) {
if (!finalResult) {
return;
}
if (arr2.find(function (item2) { return item === item2; }) === undefined) {
finalResult = false;
}
});
console.log(finalResult);

// Warn if overriding existing method
if(Array.prototype.equals)
console.warn("Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there's a framework conflict or you've got double inclusions in your code.");
// attach the .equals method to Array's prototype to call it on any array
Array.prototype.equals = function (array) {
// if the other array is a falsy value, return
if (!array)
return false;
// compare lengths - can save a lot of time
if (this.length != array.length)
return false;
for (var i = 0, l=this.length; i < l; i++) {
// Checking whether the array contains this element
if(isValueExistsInArray(this[i],array) == false) {
return false;
}
}
return true;
}
function isValueExistsInArray(value,compareToArray) {
for(var j = 0, k=compareToArray.length; j<k; j++) {
if(value == compareToArray[j]) {
return true;
}
}
return false;
}
// Hide method from for-in loops
Object.defineProperty(Array.prototype, "equals", {enumerable: false});
array1 = ['1','2','3'];
array2 = ['1','2','3'];
array3 = ['3','2','1'];
array4 = ['3','5','1'];
array5 = ['3','5','1',6];
array1.equals(array2) == true
array1.equals(array3) == true
array1.equals(array4) == false
array1.equals(array5) == false

Finally I have perfect answer for compare two array in javascript.
var array1 = ["1","2","3"];
var arr1 = array1.map(function (x) {
return parseInt(x, 10);
});
var array2 = ["3","2","1"];
var arr2 = array2.map(function (x) {
return parseInt(x, 10);
});
var finalArray1 = arr1.sort();
var finalArray2 = arr2.sort();
var is_same = finalArray1.length == finalArray2.length && finalArray1.every(function(element, index) {
return element === finalArray2[index];
});
if(is_same == true){
console.log('match');
}else{
console.log('not match');
}

Related

How to detect if an array contains any value that is a specific length

I have an array as follows:
var array = ['Bob','F', 'Nichols'];
I want to detect whether this array contains any values that are a single character long. In other words, I want to know whether there are any initials in this person's name.
var array = ['Bob','F', 'Nichols']; //true
var array = ['B','Freddy', 'Nichols']; //true
var array = ['Bob','Freddy', 'N']; //true
var array = ['B','F', 'N']; //true
var array = ['B','F', 'N']; //true
var array = ['Bob','Freddy', 'Nichols']; //false
if (anyInitials(array)) {
console.log("there are initials");
} else {
console.log("there are no initials");
}
function anyInitials(a) {
var arrayLength = a.length;
var initial = 'no';
for (var i = 0; i < arrayLength; i++) {
if (a[i].length == 1){
initial = 'yes';
}
}
return initial;
}
You can use the function some
let array = ['Bob','F', 'Nichols'];
console.log(array.some(({length}) => length === 1));
let anyInitials = a => a.some(({length}) => length === 1) ? "yes" : "no";
You can use a simple .forEach() loop like below. This loops through the array, and sets isInitial to true if the length is 1.
var array = ['Bob', 'F', 'Nichols'];
function anyInitials(a) {
var isInitial = false;
a.forEach(e => {
if (e.length == 1) {
isInitial = true;
}
});
return isInitial;
}
console.log(anyInitials(array));
You can also use .some() like below. This will return true if any element in the array has a length of 1.
var array = ['Bob', 'F', 'Nichols'];
function anyInitials(a) {
return array.some(e => e.length == 1);
}
console.log(anyInitials(array));

Finding letters in 2nd array element in 1st array element

Using javascript, I want to check if the string in the 1st array element contains all the letters of the 2nd array element. If so, return true. E.g. ["Mary", "Aarmy"] => true;
["hello", "hey"] => false.
I've tried the following code, which works for ["Mary", "Aarmy"] and ["voodoo", "no"], but doesn't work for ["hello", "hey"]. Appreciate any help, thanks!
function mutation(arr){
var str1 = arr.pop().toLowerCase();
var str2 = arr.pop().toLowerCase();
for(var i = 0; i < str2.length; i++){
if(str1.indexOf(str2[i]) !== -1){
return true;
}
else return false;
}
}
When you use pop() it'll return the last element in the array and not the first.
Also your if else is inside for and has a return statement. This does not let the for loop run completely and returns after the very first loop.
function mutation(arr){
var str2 = arr.pop().toLowerCase();
var str1 = arr.pop().toLowerCase();
console.log("str1: " + str1);
console.log("str2: " + str2);
for(var i = 0; i < str2.length; i++){
if(str1.indexOf(str2[i]) === -1){
return false;
}
}
return true;
}
arr = ["hello", "hey"];
console.log(mutation(arr));
arr = ["Mary", "Aarmy"];
console.log(mutation(arr));
Considering you can use Set, and lodash, here is another solution:
const _ = require("lodash");
function mutation(arr) {
var set1 = new Set(arr.pop().toLowerCase().split(''));
var set2 = new Set(arr.pop().toLowerCase().split(''));
return _.isEqual(set1, set2);
}
console.log(mutation(["Mary", "Aarmy"])); //true
console.log(mutation(["hello", "hey"])); //false
console.log(mutation(["voodoo", "no"])); //false
Check the working sample: https://jsfiddle.net/sayan751/3q8rtqy3/
Recursively, just for sport. If you're dealing with long (>100 char) strings, this is risky, as it relies on stack space.
const contains = function (a, b) {
if (!b) return true;
return a.indexOf(b[0]) !== -1 && contains(a, b.substring(1));
}
console.log(contains('mary', 'army')); // true
console.log(contains('hello', 'hey')); // false
Split and sort to speed up things - now only ONE comparison per set
var arr = ["Mary", "Aarmy","hello", "hey", "voodoo", "no"]
function mutation(){
var str1 = arr.pop().toLowerCase().split("").sort().join("");
var str2 = arr.pop().toLowerCase().split("").sort().join("");
return str1.indexOf(str2) !=-1;
}
while (arr.length) console.log(arr[arr.length-2],mutation())
How could function return more than one value ;) (line 6) And if second array has an array length of 3 it just checks the first arrays 3 elements. (line 4)
function mutation(arr) {
var set1 = arr[0].toLowerCase();
var set2 = arr[1].split('');
return set2.every(function(element, index, array){
if(set1.indexOf(element.toLowerCase()) != -1)
return true;
else
return false;
});
}
console.log(mutation(["Mary", "Aarmy"])); //return true
console.log(mutation(["hello", "hey"])); //return false
console.log(mutation( ["voodoo", "no"])); //return false
console.log(mutation( ["voodoo", "vo"])); //return true

counting duplicate arrays within an array in javascript

I have an array of arrays as follows:
[[3, 4], [1, 2], [3, 4]]
I wish to create a new array of arrays that has no duplicates, and has a count of the number of occurrences of each element in the first array:
[[3,4,2], [1,2,1]]
here is what I have so far:
var alreadyAdded = 0;
dataset.forEach(function(data) {
From = data[0];
To = data[1];
index = 0;
newDataSet.forEach(function(newdata) {
newFrom = newData[0];
newTo = newData[1];
// check if the point we are looking for is already added to the new array
if ((From == newFrom) && (To == newTo)) {
// if it is, increment the count for that pair
var count = newData[2];
var newCount = count + 1;
newDataSet[index] = [newFrom, newTo, newCount];
test = "reached here";
alreadyAdded = 1;
}
index++;
});
// the pair was not already added to the new dataset, add it
if (alreadyAdded == 0) {
newDataSet.push([From, To, 1]);
}
// reset alreadyAdded variable
alreadyAdded = 0;
});
I am very new to Javascript, can someone help explain to me what I'm doing wrong? I'm sure there is a more concise way of doing this, however I wasn't able to find an example in javascript that dealt with duplicate array of arrays.
Depending on how large the dataset is that you're iterating over I'd be cautious of looping over it so many times. You can avoid having to do that by creating an 'index' for each element in the original dataset and then using it to reference the elements in your grouping. This is the approach that I took when I solved the problem. You can see it here on jsfiddle. I used Array.prototype.reduce to create an object literal which contained the grouping of elements from the original dataset. Then I iterated over it's keys to create the final grouping.
var dataSet = [[3,4], [1,2], [3,4]],
grouping = [],
counts,
keys,
current;
counts = dataSet.reduce(function(acc, elem) {
var key = elem[0] + ':' + elem[1];
if (!acc.hasOwnProperty(key)) {
acc[key] = {elem: elem, count: 0}
}
acc[key].count += 1;
return acc;
}, {});
keys = Object.keys(counts);
for (var i = 0, l = keys.length; i < l; i++) {
current = counts[keys[i]];
current.elem.push(current.count);
grouping.push(current.elem);
}
console.log(grouping);
Assuming order of sub array items matters, assuming that your sub arrays could be of variable length and could contain items other than numbers, here is a fairly generic way to approach the problem. Requires ECMA5 compatibility as it stands, but would not be hard to make it work on ECMA3.
Javascript
// Create shortcuts for prototype methods
var toClass = Object.prototype.toString.call.bind(Object.prototype.toString),
aSlice = Array.prototype.slice.call.bind(Array.prototype.slice);
// A generic deepEqual defined by commonjs
// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
function deepEqual(a, b) {
if (a === b) {
return true;
}
if (toClass(a) === '[object Date]' && toClass(b) === '[object Date]') {
return a.getTime() === b.getTime();
}
if (toClass(a) === '[object RegExp]' && toClass(b) === '[object RegExp]') {
return a.toString() === b.toString();
}
if (a && typeof a !== 'object' && b && typeof b !== 'object') {
return a == b;
}
if (a.prototype !== b.prototype) {
return false;
}
if (toClass(a) === '[object Arguments]') {
if (toClass(b) !== '[object Arguments]') {
return false;
}
return deepEqual(aSlice(a), aSlice(b));
}
var ka,
kb,
length,
index,
it;
try {
ka = Object.keys(a);
kb = Object.keys(b);
} catch (eDE) {
return false;
}
length = ka.length;
if (length !== kb.length) {
if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length) {
return false;
}
} else {
return false;
}
} else {
ka.sort();
kb.sort();
for (index = 0; index < length; index += 1) {
if (ka[index] !== kb[index]) {
return false;
}
}
}
for (index = 0; index < length; index += 1) {
it = ka[index];
if (!deepEqual(a[it], b[it])) {
return false;
}
}
return true;
};
// Recursive function for counting arrays as specified
// a must be an array of arrays
// dupsArray is used to keep count when recursing
function countDups(a, dupsArray) {
dupsArray = Array.isArray(dupsArray) ? dupsArray : [];
var copy,
current,
count;
if (a.length) {
copy = a.slice();
current = copy.pop();
count = 1;
copy = copy.filter(function (item) {
var isEqual = deepEqual(current, item);
if (isEqual) {
count += 1;
}
return !isEqual;
});
current.push(count);
dupsArray.push(current);
if (copy.length) {
countDups(copy, dupsArray);
}
}
return dupsArray;
}
var x = [
[3, 4],
[1, 2],
[3, 4]
];
console.log(JSON.stringify(countDups(x)));
Output
[[3,4,2],[1,2,1]]
on jsFiddle
After fixing a typo I tried your solution in the debugger; it works!
Fixed the inner forEach-loop variable name to match case. Also some var-keywords added.
var alreadyAdded = 0;
dataset.forEach(function (data) {
var From = data[0];
var To = data[1];
var index = 0;
newDataSet.forEach(function (newData) {
var newFrom = newData[0];
var newTo = newData[1];
// check if the point we are looking for is already added to the new array
if ((From == newFrom) && (To == newTo)) {
// if it is, increment the count for that pair
var count = newData[2];
var newCount = count + 1;
newDataSet[index] = [newFrom, newTo, newCount];
test = "reached here";
alreadyAdded = 1;
}
index++;
});
// the pair was not already added to the new dataset, add it
if (alreadyAdded == 0) {
newDataSet.push([From, To, 1]);
}
// reset alreadyAdded variable
alreadyAdded = 0;
});
const x = [[3, 4], [1, 2], [3, 4]];
const with_duplicate_count = [
...x
.map(JSON.stringify)
.reduce( (acc, v) => acc.set(v, (acc.get(v) || 0) + 1), new Map() )
.entries()
].map(([k, v]) => JSON.parse(k).concat(v));
console.log(with_duplicate_count);

How to Compare two Arrays are Equal using Javascript? [duplicate]

This question already has answers here:
How to compare arrays in JavaScript?
(55 answers)
Closed 3 years ago.
I want position of the array is to be also same and value also same.
var array1 = [4,8,9,10];
var array2 = [4,8,9,10];
I tried like this
var array3 = array1 === array2 // returns false
You could use Array.prototype.every().(A polyfill is needed for IE < 9 and other old browsers.)
var array1 = [4,8,9,10];
var array2 = [4,8,9,10];
var is_same = (array1.length == array2.length) && array1.every(function(element, index) {
return element === array2[index];
});
THE WORKING DEMO.
A less robust approach, but it works.
a = [2, 4, 5].toString();
b = [2, 4, 5].toString();
console.log(a===b);
var array3 = array1 === array2
That will compare whether array1 and array2 are the same array object in memory, which is not what you want.
In order to do what you want, you'll need to check whether the two arrays have the same length, and that each member in each index is identical.
Assuming your array is filled with primitives—numbers and or strings—something like this should do
function arraysAreIdentical(arr1, arr2){
if (arr1.length !== arr2.length) return false;
for (var i = 0, len = arr1.length; i < len; i++){
if (arr1[i] !== arr2[i]){
return false;
}
}
return true;
}
A more modern version:
function arraysEqual(a, b) {
a = Array.isArray(a) ? a : [];
b = Array.isArray(b) ? b : [];
return a.length === b.length && a.every((el, ix) => el === b[ix]);
}
Coercing non-array arguments to empty arrays stops a.every() from exploding.
If you just want to see if the arrays have the same set of elements then you can use Array.includes():
function arraysContainSame(a, b) {
a = Array.isArray(a) ? a : [];
b = Array.isArray(b) ? b : [];
return a.length === b.length && a.every(el => b.includes(el));
}
You could try this simple approach
var array1 = [4,8,9,10];
var array2 = [4,8,9,10];
console.log(array1.join('|'));
console.log(array2.join('|'));
if (array1.join('|') === array2.join('|')) {
console.log('The arrays are equal.');
} else {
console.log('The arrays are NOT equal.');
}
array1 = [[1,2],[3,4],[5,6],[7,8]];
array2 = [[1,2],[3,4],[5,6],[7,8]];
console.log(array1.join('|'));
console.log(array2.join('|'));
if (array1.join('|') === array2.join('|')) {
console.log('The arrays are equal.');
} else {
console.log('The arrays are NOT equal.');
}
If the position of the values are not important you could sort the arrays first.
if (array1.sort().join('|') === array2.sort().join('|')) {
console.log('The arrays are equal.');
} else {
console.log('The arrays are NOT equal.');
}
If you comparing 2 arrays but values not in same index, then try this
var array1=[1,2,3,4]
var array2=[1,4,3,2]
var is_equal = array1.length==array2.length && array1.every(function(v,i) { return ($.inArray(v,array2) != -1)})
console.log(is_equal)
Use lodash.
In ES6 syntax:
import isEqual from 'lodash/isEqual';
let equal = isEqual([1,2], [1,2]); // true
Or previous js versions:
var isEqual = require('lodash/isEqual');
var equal = isEqual([1,2], [1,2]); // true
Here goes the code. Which is able to compare arrays by any position.
var array1 = [4,8,10,9];
var array2 = [10,8,9,4];
var is_same = array1.length == array2.length && array1.every(function(element, index) {
//return element === array2[index];
if(array2.indexOf(element)>-1){
return element = array2[array2.indexOf(element)];
}
});
console.log(is_same);
function isEqual(a) {
if (arrayData.length > 0) {
for (var i in arrayData) {
if (JSON.stringify(arrayData[i]) === JSON.stringify(a)) {
alert("Ya existe un registro con esta informacion");
return false;
}
}
}
}
Check this example
Try doing like this: array1.compare(array2)=true
Array.prototype.compare = function (array) {
// if the other array is a falsy value, return
if (!array)
return false;
// compare lengths - can save a lot of time
if (this.length != array.length)
return false;
for (var i = 0, l=this.length; i < l; i++) {
// Check if we have nested arrays
if (this[i] instanceof Array && array[i] instanceof Array) {
// recurse into the nested arrays
if (!this[i].compare(array[i]))
return false;
}
else if (this[i] != array[i]) {
// Warning - two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
}

comparing two dimensional array js

I am coding something in JS and I have to test code - I have to check if elements in 2 arrays are the same.
So I've got an array: boreholes = [[66000, 457000],[1111,2222]....]; and I want to check if this array contain element for eg. [66000,457000] so I did:
boreholes.indexOf([66000,457000]) but it returns -1, so I iterate trough array by:
for (var i = 0; i< boreholes.length; i++){
if (boreholes[i] == [66000, 457000]){
console.log('ok');
break;
}
};
but still I've got nothing. Can someone explain me what am I doing wrong?
You are comparing distinct objects. When comparing objects, the comparison only evaluates to true when the 2 objects being compared are the same object. I.E
var a = [1,2,3];
var b = a;
a === b //true
b = [1,2,3];
a === b //false, b is not the same object
To compare arrays like this, you need to compare all of their elements separately:
for (var i = 0; i < boreholes.length; i++) {
if (boreholes[i][0] == 66000 && boreholes[i][1] == 457000) {
console.log('ok');
break;
}
}
You cannot compare arrays like array1 == array2 in javascript like you're trying to do here.
Here is a kludge method to compare two arrays:
function isEqual(array1, array2){
return (array1.join('-') == array2.join('-'));
}
You can now use this method in your code like:
for (var i = 0; i< boreholes.length; i++){
if (isEqual(boreholes[i], [66000, 457000]){
console.log('ok');
break;
}
};
Currently I had the same problem, did it with the toString() method
var array1 = [1,2,3,[1,2,3]]
var array2 = [1,2,3,[1,2,3]]
array1 == array2 // false
array1.toString() == array2.toString() // true
var array3 = [1,2,3,[1,3,2]]
// Take attention
array1.toString() == array3.toString() // false
You could also doing it with the Underscore.js-framework for functional programming.
function containsElements(elements) {
_.find(boreholes, function(ele){ return _.isEqual(ele, elements); });
}
if(containsElements([66000, 457000])) {
console.log('ok');
}
The question isn't quite clear if there can be more than 2 elements in an array, so this might work
var boreholes = [[66000, 457000],[1111,2222]];
var it = [66000, 457000];
function hasIt(boreholes, check) {
var len = boreholes.length;
for (var a = 0; a < len; a++) {
if (boreholes[a][0] == check[0] && boreholes[a][1] == check[1]) {
// ok
return true;
}
}
return false;
}
if (hasIt(boreholes, it)) {
// ok, it has it
}

Categories