This question already has answers here:
Simplest code for array intersection in javascript
(40 answers)
Closed 7 years ago.
I have two arrays like this:
var x = ['1','2','6'];
var y = ['4', '5','6'];
How do I find duplicates in two arrays in pure JavaScript and I would like to avoid using a loop?
Output - duplicates: 6
Try something like this:
var x = ['1','2','6'];
var y = ['4', '5','6'];
var overlap = x.filter(function(v,i,a){
return y.indexOf(v) > -1;
});
console.log(overlap); // ['6']
Does this work for your purpose?
MDN docs for filter
Try this
var x = ['1','2','6'];
var y = ['4', '5','6'];
var duplicate = [];
for (var i=0; i<y.length; i++) {
var index = x.indexOf(y[i]);
if (index > -1) {
duplicate.push(x[index]);
}
}
Output: ["6"]
Related
This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 2 years ago.
In the function below, I am trying to get the values of the imported_Id that are not present in the old_Id array, and store them them into a new array add_IDs. In the example below, I would want to store values 1004 and 1005 in a new array. I have tried using the filter() method and other variations of for loops but can't seem to get it right. Any suggestions on a solutions would be greatly appreciated!
function myfunction() {
const old_id = ["1000","1001","1002","1003"];
const imported_id = ["1000","1001","1002","1003","1004","1005"];
const add_ids = [];
for(var x = 0; x < imported_id.length; x++){
const append_id = [];
for(var y = 0; y < old_id.length; y++) {
if (old_id[y].indexOf(imported_id[x]) == -1){
append_id.push(imported_id[x]);
}
}
add_ids.push(append_id[x]);
}
Logger.log(add_ids);
}
Use filter and array.includes() to check if the number is in the second array
const old_id = ["1000", "1001", "1002", "1003"];
const imported_id = ["1000", "1001", "1002", "1003", "1004", "1005"];
res = imported_id.filter((n) => !old_id.includes(n));
console.log(res);
When your script is modified, I would like to propose the following 2 patterns. In this case, both patterns are the same result.
Pattern 1:
In this pattern, your script is a bit modified.
Modification point:
In this case, I think that append_id can be used for checking the duplicate values.
For example, in this modification, when the duplicate values between old_id and imported_id are existing, the length of append_id is not 0. This is used.
By checking the length of append_id, the result value can be retrieved.
Modified script:
const old_id = ["1000","1001","1002","1003"];
const imported_id = ["1000","1001","1002","1003","1004","1005"];
const add_ids = [];
for (var x = 0; x < imported_id.length; x++) {
const append_id = [];
for (var y = 0; y < old_id.length; y++) {
if (old_id[y].indexOf(imported_id[x]) != -1) { // or if (old_id[y] == imported_id[x]) {
append_id.push(imported_id[x]);
}
}
if (append_id.length == 0) {
add_ids.push(imported_id[x]);
}
}
console.log(add_ids);
Pattern 2:
In this pattern, "Array.prototype.indexOf()" is used instead of "String.prototype.indexOf()".
Modification point:
When you use indexOf, by using "Array.prototype.indexOf()" index of "String.prototype.indexOf()", I think that inner for loop is not required.
Modified script:
const old_id = ["1000","1001","1002","1003"];
const imported_id = ["1000","1001","1002","1003","1004","1005"];
const add_ids = [];
for (var x = 0; x < imported_id.length; x++) {
if (old_id.indexOf(imported_id[x]) == -1) {
add_ids.push(imported_id[x]);
}
}
console.log(add_ids);
References:
String.prototype.indexOf()
Array.prototype.indexOf()
This question already has answers here:
Zip arrays in JavaScript?
(5 answers)
Closed 5 years ago.
In my javascript function i have two single array like this:
var row = ["var1","var2","var3"];
var col = ["res1","res2","res3"];
i would create a multidimensional array like:
[["var1","res1"],["var2","res2"],["var3","res3"]]
i tried:
new Array(m).fill(new Array(n).fill(0));
or solution like:
var dict = [[]];
for (i = 0; i < descendents.length; i++) {
e = descendents[i];
dict[i] = dict[i][e.id]
dict[i] = dict[i][e.value]
}
but the result is not correct for me. i don't know how achieve this
Thanks in advance
Use Array#map to generate a new array based on existing.
var row = ["var1", "var2", "var3"];
var col = ["res1", "res2", "res3"];
// iterate and generate new array based on row array element
// and fetch element from col using the same index
var res = row.map((v, i) => [v, col[i]]);
console.log(res)
Or with Array.from with a map function.
var row = ["var1", "var2", "var3"];
var col = ["res1", "res2", "res3"];
var res = Array.from({ length: row.length }, (_, i) => [row[i], col[i]]);
console.log(res)
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.
This question already has answers here:
How to compare arrays in JavaScript?
(55 answers)
Closed 8 years ago.
I have two multidimensional arrays and need to remove all the arrays from array A that exist in array B. I've tried it this way with no luck:
var arrayA = [[0,1], [2,0], [0,3], [4,0], [0,5]];
var arrayB = [[0,1], [0,3]];
arrayA = arrayA.filter( function( el ) {
return arrayB.indexOf( el ) < 0;
} );
alert(arrayA);
This works when the elements in arrayA and arrayB are single values and but when they are arrays. Not sure what I am doing wrong?
Assuming the inner arrays are always in the same order to match:
for (var i = 0; i < arrayA.length; i++) {
for (var j = 0; j < arrayB.length; j++) {
if (JSON.stringify(arrayA[i]) == JSON.stringify(arrayB[j])) {
arrayA.splice(i, 1);
break;
}
}
}
Fiddle: http://jsfiddle.net/o2qk7hjd/
Array.prototype.indexOf uses strict equals comparison to check if elements are equal. This wont work for reference types since [] === []; is false. You can either use #tymeJV solution which is O(lenA*lenB) complexity or preindex arrayB making it O(lenA + lenB)
Demo.
function index(arr) {
return arr.reduce(function(acc, item){
return acc[JSON.stringify(item)] = item, acc
}, {});
}
var arrayA = [[0,1], [2,0], [0,3], [4,0], [0,5]];
var arrayB = [[0,1], [0,3]];
var indexB = index(arrayB);
arrayA = arrayA.filter( function( el ) {
return !(JSON.stringify(el) in indexB);
} );
console.log(arrayA);
UPD
If the order of elements inside inner arrays is not quaranteed you can use sort. This will make this task O(lenA*log(lenA) + lenB*log(lenB))
Demo 2.
You can do it like this
var arr = arrayA.map(function(x){ return x + "" }); // convert the array to string
arrayB.forEach(function(e) {
var idx = (arr.indexOf(e + "")); // find the index
arr.splice(idx, 1); // remove it
});
arrayA = arr.map(function(x) { return x.split(","); });
This question already has answers here:
Javascript equivalent of Python's zip function
(24 answers)
Closed 8 years ago.
var arrayOne = [a,b,c];
var arrayTwo = [d,e,f];
How can I combine the two arrays in JavaScript so that the result will be:
var array = [a,d,b,e,c,f];
Note: This is not concatenating two arrays. This is merging the two arrays so the indices look like [0,0,1,1,2,2].
Assuming that the two arrays are equal of length, this should do the trick:
var arrayThree = [];
for(var i = 0; i < arrayOne.length; i++){
arrayThree.push(arrayOne[i], arrayTwo[i]);
}
If they aren't the same length and you would have the two arrays:
var a = [a,b,c,d];
var b = [e,f];
I assume you would want the the following result
var c = [a,e,b,f,c,d];
That should do the trick:
var c = [];
while(Math.min(a.length, b.length)){
c = c.concat(a.splice(0,1), b.splice(0,1));
//Or c = c.concat(b.splice(0,1), a.splice(0,1));
//depending on the order
}
a.length ? c = c.concat(a) : c = c.concat(b);
//Here is a = [c,d] and b = []
You can use jQuery's unique method along with concat
var a = [1,2,3];
var b = [2,3,4];
var c = a.concat(b); // [1,2,3,2,3,4]
c = $.unique(c); // [1, 2, 3, 4]
You may need to sort the array as needed.