Related
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');
}
I have searched on here and have not found a solution. Obviously I will be corrected if I am wrong. What I am trying to do is return values that do not have a duplicates in an array.
Examples:
myArr = [2,1,2,3] // answer [1,3]
myArr = [3,1,2,2,3] // answer [1]
I would post some code but I have not been able to figure this out myself and the only code examples I have found are for removing any duplicate values.
The possible solution above is to return no duplicates... I am trying to return values that are don't have duplicates.
One option is to use the optional second argument to indexOf to find duplicate indexes. Consider that for a given element e and an index i:
if e is the first of two identical elements in the array, indexOf(e) will return i and indexOf(e, i + 1) will return the index of the second element.
if e is the second of two identical elements in the array, indexOf(e) will return the index of the first element, and indexOf(e, i + 1) will return -1
if e is a unique element, indexOf(e) will return i and indexOf(e, i + 1) will return -1.
Therefore:
myArr.filter(function (e, i, a) {
return a.indexOf(e) === i && a.indexOf(e, i + 1) === -1
});
var isUnique = function(v,i,arr){
// return true if the first occurrence is the last occurrence
return ( arr.indexOf(v) === arr.lastIndexOf(v) );
};
var uniqueVals = myArr.filter(isUnique);
console.log( uniqueVals );
If is not an associative array (your case):
var myArr = [1,2,2,3,4,4,1,5];
var myNewArr = [];
if (myArr.length > 0 )
{
myNewArr[0] = myArr[myArr.length-1];
}
var count = 1;
myArr.sort();
for (var i = myArr.length - 2; i >= 0; i--) {
if(myArr[i] != myArr[i-1])
{
myNewArr[count] = myArr[i];
count++;
}
}
var yourArray = [1, 2, 1, 3];
var uniqueValues = [];
$.each(yourArray, function (i, value) { //taking each 'value' from yourArray[]
if ($.inArray(value, uniqueValues) === -1) {
uniqueValues.push(value); // Pushing the non - duplicate value into the uniqueValues[]
}
});
console.log(uniqueValues);
Result: [1,2,3];
I have a question of JS arrays.
Example:
var fullArr = [1,2,3,4];
var partArr = [2,3];
var newArr = [];
We have a main array fullArr and a partial array partarr. I want to create a function/filter, which is looking for existing items in fullArr and not in partArr.
In this example above newArr must be equal to [1,4].
I've tried doing something like this, but it's not working properly.
for (var k in fullArray) { // [1,2,3,4]
for (var j in selectedArray) { // [1,4]
if (fullArray[k] == selectedArray[j]) {
newArray.splice(selectedArray[j] - 1, 1); // must be [2,3]
break;
}
}
}
What is a good way of making this? Thanks.
Here's one
var newArr = fullArr.filter(function(f) { // The filter() method creates a new array with all elements that pass the test implemented by the provided function.
return partArr.indexOf(f) == -1; // The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
})
to impress the girls, you can also
var newArr = fullArr.filter(function(f) {
return !~partArr.indexOf(f);
})
Here is the code for your requirement.
var fullArr = [1,2,3,4];
var partArr = [2,3];
var newArr = [];
for(var i=0;i<fullArr.length;i++){
if(partArr.indexOf(fullArr[i]) == -1)
newArr.push(fullArr[i]);
};
Here is the working Link
Hope it works :)
In fact, you want a common part between arrays. Obviously you can choose splice or indexOf to have O(n * m) or even O(m * n^2) performance. It's obviously suboptimal for any array larger than few elements
Or you can use objects as hash maps to find differences in (in worst case) O(n + m log m):
var fullArr = [1,2,3,4];
var partArr = [2,3];
var temporaryObject = Object.create(null);
partArr.forEach(el=>temporaryObject[el] = true); // temporaryObject after this operation is {"2": true, "3": true}
var newArr = fullArr.filter(el=>temporaryObject[el]);
In this example I have used ES6 feature called "arrow functions". It translates to following ES5 code:
var partArr = [2, 3];
var temporaryObject = Object.create(null);
partArr.forEach(function (el) {
temporaryObject[el] = true;
}); // temporaryObject after this operation is {"2": true, "3": true}
var newArr = fullArr.filter(function (el) {
return temporaryObject[el];
});
You can use the filter() function that works on arrays:
var newArr = fullArr.filter(function(val, i, arr) {
return partArr.indexOf(val) === -1;
});
This will return a new array containing the values of every iteration that returns true.
Should you ever need to do this on an object in the future a great way is to first convert the object keys to an array and then run the filter:
Object.keys(myObj).function(val, i, arr) {
return partArr.indexOf(val) === -1;
});
Here are few other approaches:
var fullArr = [1,2,3,4];
var partArr = [2,3];
var newArr = [];
1.
fullArr.map(function(element){
if(partArr.indexOf(element) === -1) newArr.push(element);
})
console.log(newArr);
2.
for(i in fullArr){
if(partArr.indexOf(fullArr[i]) === -1) newArr.push(fullArr[i]);
}
console.log(newArr);
3.
fullArr.forEach(function(element){
if(partArr.indexOf(element) === -1) newArr.push(element);
})
console.log(newArr);
I have two arrays
var arr1 = [
{'id':'1','name':'test1','value':'star','role':['monitor']},
{'id':'2','name':'test2','value':'player','role':['monitor','Supervisor']},
{'id':'3','name':'test3','value':'saviour','role':['Supervisor']},
{'id':'4','name':'test4','value':'rock','role':['monitor']},
{'id':'5','name':'test5','value':'rocky','role':['boxer','monitor']}
]
var arr2 = ['Supervisor','monitor'];
I want to get the result where arr2 values is properly matched with arr1 roles values
Persons having both the category should be pushed to arr3.
So result should be {'id':'2','name':'test2','value':'player','role':['monitor','Supervisor']}.
if arr2 has one value then we can use arr1.indexOf(arr2[0])!='-1' but how to satisfy the "and" condition in the for loop..
I don't want to use this if possible, but it's all I can think of:
if( arr1.indexOf(arr2[0])!='-1' && arr1.indexOf(arr2[1])!='-1'){
return arr1[i];
}
Like #Marc B and #Terry say, you have just to do an intersection.
Here's a version without Jquery :
function intersection(a, b)
{
var result = [], ai = 0, bi = 0;
a.sort();
b.sort();
while( a.length > ai && b.length > bi )
{
if(a[ai] < b[bi] ){
ai++;
}
else if(a[ai] > b[bi] ){
bi++;
}
else
{
result.push(a[ai]);
ai++;
bi++;
}
}
return result;
}
var arr1 = [
{'id':'1','name':'test1','value':'star','role':['monitor']},
{'id':'2','name':'test2','value':'player','role':['monitor','Supervisor']},
{'id':'3','name':'test3','value':'saviour','role':['Supervisor']},
{'id':'4','name':'test4','value':'rock','role':['monitor']},
{'id':'5','name':'test5','value':'rocky','role':['boxer','monitor']}
]
var arr2 = ['Supervisor','monitor'];
var arr3 = [];
arr1.forEach(function(value){
if(intersection(value.role, arr2).length === arr2.length){
arr3.push(value);
}
});
console.log(arr3);
The main trick here is the equality of the arrays.
// Assuming we have array 'equals' method which compares the array equality
// el['role'] == arr2 won't work
var result = arr1.filter(function(el){
return el['role'].equals(arr2);
});
So, we can see that we only have to deal with array equality.
This post How to compare arrays in JavaScript? has a lot of discussion about it. Someone has even implemented 'equals' method.
You can use a jQuery one-liner to compare array—and the best thing is that they don't have to be in the exact same order. Simply use the .not() method, previously mentioned before.
The only trick is to use $.each() to loop through your first array, and compare the array of the role object against arr2 using .not():
var arr1 = [
{'id':'1','name':'test1','value':'star','role':['monitor']},
{'id':'2','name':'test2','value':'player','role':['monitor','Supervisor']},
{'id':'3','name':'test3','value':'saviour','role':['Supervisor']},
{'id':'4','name':'test4','value':'rock','role':['monitor']},
{'id':'5','name':'test5','value':'rocky','role':['boxer','monitor']}
]
var arr2 = ['Supervisor','monitor'];
var arr3 = [];
$.each(arr1, function(idx,person){
if($(person.role).not(arr2).length === 0 && $(arr2).not(person.role).length === 0) {
arr3.push(person);
}
});
console.log(arr3);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm working on project where I have array simmilar to this
var sortBp = [ 'height58em', 'width480px', 'width768px', 'width959px', 'width767px', 'width767px' ];
I want to sort this array in ascending order while eleminating repeated values so that result should be
var sortBp = [ 'height58em', 'width480px', 'width767px', 'width768px', 'width959px' ];
I'm using following function to sort array in ascending array but how do I eliminate immediate values ?? (In above case 'width767px')
var sortBp = bpArrays.sort(function(a, b) {
a = a.replace(/[a-z]/g, '');
b = b.replace(/[a-z]/g, '');
return a - b;
});
Firstly, you can't eliminate elements while sorting. You have to sort the array first, then remove duplicates. Your solution using Array.prototype.filter and Array.prototype.indexOf might be good for unsorted array, but since your array is sorted, it's overhead here(takes O(n) for each). Instead you can just loop through the array and compare element with previous one.
function uniq(array) {
var i, l = array.length, result = [];
for (i = 0; i < l; i++) {
if (result[result.length - 1] != array[i]) {
result.push(array[i]);
}
}
return result;
}
This is same with Underscore and Prototype's uniq() implemention.
Last note: remember that this will work fine with sorted array only.
If this is not homework, i.e. you aren't required to implement the algorithm yourself, you could use a combination of sortBy and uniq functions.
sortBp = [ 'height58em', 'width480px', 'width768px', 'width959px', 'width767px', 'width767px' ];
_.uniq(_.sortBy(sortBp, function(x) {return x;}), true);
This returns:
["height58em", "width480px", "width767px", "width768px", "width959px"]
Note that this will be sort by lexical order, and if you do not wish this to happen, simply substitute the identity function function(x) {return x;} with your own logic.
Array.prototype.contains = function(k) {
for ( var p in this)
if (this[p] === k)
return true;
return false;
};
inputArray.sort();
function uniqueArray(inputArray){
result=[];
for(var i in inputArray){
if(!result.contains(inputArray[i])){
result.push(inputArray[i]);
}
}
return result;
}
Found It !!
var sortBp = [ 'height58em', 'width480px', 'width768px', 'width959px', 'width767px', 'width767px' ];
uniqueArray = sortBp.filter(function(elem, pos) {
return sortBp.indexOf(elem) == pos;
});
EDIT :
I have found another solution here : http://dreaminginjavascript.wordpress.com/2008/08/22/eliminating-duplicates/
function eliminateDuplicates(arr) {
var i, len=arr.length, out=[], obj={};
for (i=0;i<len;i++) {
obj[arr[i]]=0;
}
for (i in obj) {
out.push(i);
}
return out;
}