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
}
Related
I have the following function which takes some values that the user has entered and creates JavaScript objects from those values, then puts those objects in an array and returns the array:
function createObjects() {
var objectArray = [];
for (var i = 0; i < someCount; i++) {
var object = {
property1: someProperty1,
property2: someProperty2,
property3: someProperty3,
property4: someProperty4
};
objectArray.push(object);
}
return objectArray;
}
Now, I want to compare these objects' properties and determine whether any two contain all of the same values for property1, property2, property3, and property4. If any two of these objects have all four of the same values for these properties, I want a validation check to return false. Here is what I have so far:
function objectsAreUnique() {
var objects = createObjects();
for(var i = 0; i < objects.length; i++) {
//need to determine whether all four of the properties are the same for any two objects
//if(objectsAreSame) { return false; }
}
return true;
}
I have a few ideas, but I'm interested to see what is the most efficient way to achieve this. Thanks!
If you can guarantee that the properties will always be inserted in the same order (which will be the case if using an object literal as in your example), you can do this in ~O(n) using JSON.stringify and a Set:
function objectsAreUnique() {
const objects = createObjects();
return (new Set(objects.map(o => JSON.stringify(o)))).size == objects.length;
}
First, create a function to test whether two objects are the same. You can enter each property individually, or get creative with the JSON.stringify function
properties individually:
function objectsIdentical(obj1, obj2) {
return obj1.property1 == obj2.property1 && obj1.property2 == obj2.property2 && obj1.property3 == obj2.property3 && obj1.property4 == obj2.property4;
}
JSON.stringify (recommended for objects with many properties)
function objectsIdentical(obj1, obj2) {
return JSON.stringify(obj1).replace(/^.|.$/g, "").split(",").sort().join(",") == JSON.stringify(obj2).replace(/^.|.$/g, "").split(",").sort().join(",");
}
Then, you can use a for loop to check if any of them are identical.
for (let i=0; i<objects.length-1; i++) {
for (let j=i+1; j<objects.length; j++) {
if (objectsIdentical(objects[i], objects[j])) {
return false;
}
}
}
return true;
If you're familiar with the "some" function, you can use that.
return !objects.some((v, i) => objects.slice(i+1).some(w => objectsIdentical(v, w)))
function objectsAreUnique() {
var objects = createObjects();
var stringifiedAndSorted = objects.map(obj => JSON.stringify(obj)).sort()
for(var i = 0; i < stringifiedAndSorted.length-1; i++) {
if(i === i+1)
return false;
}
return true;
}
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');
}
This question already has answers here:
What is the fastest or most elegant way to compute a set difference using Javascript arrays?
(14 answers)
Closed 8 years ago.
How can i compare this two arrays and create a new array (filtered) based on if any number in Array1 exist in Array2. Both arrays is dynamic and can have different lengths.
Array1 = 3796, 3831, 3858, 3860
Array2 = 3796, 4566, 2932, 3831, 3290, 3858, 4599, 3293 etc etc..
In this case i want my output to be:
Array3 = 4566, 2932, 3290, 4599, 3293
I assume you are comparing normal array. If no, you need to change for loop to for .. in loop.
function arr_diff(a1, a2)
{
var a=[], diff=[];
for(var i=0;i<a1.length;i++)
a[a1[i]]=true;
for(var i=0;i<a2.length;i++)
if(a[a2[i]]) delete a[a2[i]];
else a[a2[i]]=true;
for(var k in a)
diff.push(k);
return diff;
}
The function will return array having difference of the two arrays
This may be the shortest solution:
function diff(a, b) {
var c = [].slice.call(a.length > b.length ? a : b); // clone the longest array
return c.filter(function(c) { return a.indexOf(c) < 0 }); // filter out intersects
}
var a = [3796, 3831, 3858, 3860],
b = [3796, 4566, 2932, 3831, 3290, 3858, 4599, 3293];
console.log( diff(a, b) ); // [4566, 2932, 3290, 4599, 3293]
You can try this:
function in_array(needle, haystack){
for (var i = 0; i < haystack.length; i++){
if (needle == haystack[i]) return true;
}
return false;
}
for (var i = 0; i < array1.length; i++){
if (!in_array(array1[i], array2){
var index = array1.indexOf(array1[i]);
array1.splice(index, 1);
}
}
I have not tested it, but i guess it should work.
I am having trouble checking the contents of an array contained within a main array.
Example:
I have two arrays
var main = [[1,2,3],
[4,5,6]];
var compare = [1,2,4,5,6]
I want to compare the array "compare" with each array within the array "main" to see if it contains any of the numbers. The result would be something I could then test against (boolean or the index position).
I tried indexOf and couldn't figure it out.
Edit
This should still return true:
var main = [[1,2,3], // returns false
[4,5,6], // returns false
[7,8,9], // returns true
[2,3,7]]; // returns true
var compare = [2,3,4,6,7,8,9]
** Update w/ Solution ***
I needed to check if compare array's contents matched any of the subarrays in main. Here's what I came up with:
var main = [[1, 2, 3],
[4,5,6]];
var counter = 0;
var counter2 = 0;
var compare = [4,1,3,2];
for (var i = 0; i <= compare.length; i++) {
// Sorting
compare.sort();
if (main[0].indexOf(compare[i]) > -1) {
counter++;
console.log("Added a point to counter 1");
} else if (main[1].indexOf(compare[i]) > -1) {
counter2++;
console.log("Added a point to counter 2");
} else {
console.log("No points added");
}
}
// if any of the counters have 3 marks, then the player hit it 3 times.
if (counter == 3 || counter2 === 3){
console.log("A counter is at 3");
}
Any feedback on what I came up with? What's a better way of doing this?
You'll need 2 loops, the first to iterate over your array of arrays, the next to check for existing elements within the current array:
for (var i = 0; i < main.length; i++) {
for (var j = 0; j < main[i].length; j++) {
if (compare.indexOf(main[i][j]) {
//compare has a number from the current array! main[i][j] exists in compare!
}
}
}
Take a look at lodash library, the have that exact functionality written already
You can use built-in array methods:
var result = main.map(function(xs) {
return xs.some(function(x) {
return compare.indexOf(x) > -1
})
})
It will return [true, true]
Following, two of the possible solutions:
Suppose:
var main = [[1,2,3],
[4,5,6],
[7,8,9],
[2,3,7],
[5,1,10]];
var compare = [2,3,4,6,7,8,9];
First solution: return true if any element of the main inner array is included in the master one which is compare:
var result1= main.map(function(element,index,array){
return element.reduce(function(previousValue, currentValue, index, array){
return (previousValue || (compare.indexOf(currentValue) >= 0));
}, false);
});
This solution gives the following result:
result1 = [true,true,true,true,false]
Second solution: return the index of the main inner array elements in compare:
var result2= main.map(function(element,index,array){
return element.map(function(element,index,array){
return (compare.indexOf(element));
});
});
This solution gives the following result:
result2 = [[-1,0,1],[2,-1,3],[4,5,6],[0,1,4],[-1,-1,-1]]
Check this link jsfiddle to see a working example.
Hope it's useful!
I'm trying to create an Array with unique objects. I've got json data from a tounament that I want to order by pools. Each match got his own pooldata so he will push the pool data of each match to the array. This will create an Array of 5 of the same pool values. This is my code:
var arr = [];
for (var i = 0; i < data.objects.length; i++){
obj = {
poolId: data.objects[i].pool.id,
poolLetter: data.objects[i].pool.name
};
if (arr.indexOf(obj) == -1) {
arr.push(obj);
}else{}
}
The problem is that the obj you are generating in the loop is not going to be the same object inside your arr array, they will have different signatures, so you can't use indexOf in this instance.
Instead, you will have to loop over the arr array to see if you can find any elements with the same poolId or poolLetter:
var arr = [];
for (var i = 0; i < data.objects.length; i++){
obj = {
poolId: data.objects[i].pool.id,
poolLetter: data.objects[i].pool.name
};
// Do the insert if arr doesn't already contain this poolId
if(!arrayContains(arr, obj.poolId)) arr.push(obj);
}
// Helper function to find an instance of poolId in the given array
function arrayContains(arr, poolId) {
for(var x = 0; x < arr.length; x++) {
if(arr[x].poolId === poolId) {
return true;
}
}
return false;
}
Here is a fiddle which demonstrates the above.
indexOf compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).
then
var obj1 = { a:1};
var obj2 = { a:1};
obj1 === obj2; // wrong
when you write "var obj1={a:1}" ,javascript create a new object.
You can use Array Prototype. Just pass the object.
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
Use the following
alert([1, 2, 3].contains(2)); //true
alert([1, 2, 3].contains('2')); //false
There is also a jQuery solution. I know you didn't asked for a jQuery answer. But maybe you want use it.
jQuery.inArray() returns the index of a specified value and returns -1 if not found.
http://api.jquery.com/jQuery.inArray/