How to deduplicate a merged array? - javascript

I want to merge two arrays which have some duplicated values into one array which has no duplicates. I am using concat but the result is all value.
var a = [1,2,2];
var b = [1,2,3,3];
var c = a.concat(b);
console.log(c);
Expected output:
[1, 2, 3]

Merge them into a Set, and turn that set back into an array:
var a = [1,2,2];
var b = [1,2,3,3];
var c = [...new Set([...a, ...b])];
console.log(c);
You can also use concat and Array.from as an alternative to spread syntax if necessary:
var a = [1,2,2];
var b = [1,2,3,3];
var c = Array.from(new Set(a.concat(b)));
console.log(c);

Add both of them to a Set, which is a data structure that ignores duplicates.

Related

How to add one array object to the another array object in javascript

my scenario is:
var a=[{name:"Rambabu",id:"101"},{name:"Divya",id:"102"}];
var b=[{name:"manu",id:"103"},{name:"sudha",id:"104"}];
var c= a array + b array data objects.
Expected output:
c= [{name:"Rambabu",id:"101"},{name:"Divya",id:"102"},{name:"manu",id:"103"},{name:"sudha",id:"104"}]
Use .concat
var a=[{name:"Rambabu",id:"101"},{name:"Divya",id:"102"}];
var b=[{name:"manu",id:"103"},{name:"sudha",id:"104"}];
var c = a.concat(b);
console.log(c);
Or you can also use spread operator...
var a=[{name:"Rambabu",id:"101"},{name:"Divya",id:"102"}];
var b=[{name:"manu",id:"103"},{name:"sudha",id:"104"}];
var c = [...a, ...b];
console.log(c);

Remove Duplicate elements from Array - Javascript (No JQuery & ECMAScript)

Case: We have 'n' number of arrays stored in an array (Array of Arrays). Now that each child array in this parent array can have elements that may or may not be present in other child arrays. Output - I need to create an array which has the all the elements present in all the child arrays excluding the duplicates.
I do not want to concatenate all the arrays into a single array and use unique method to filter out. I need to create unique array then and there during iteration.
Ex:
var a[] = [1,2,3,4,5];
var b[] = [1,2,7,8];
var c[] = [1,2,3,4,5,6,7,8];
var d[] = [9,10,11,12];
var arr[] = [a,b,c,d]
Output must be [1,2,3,4,5,6,7,8,9,10,11,12]
P.S: I can concat the arrays and use jquery unique function to resolve this, but i need a solution in javascript alone. Thanks
You can use array#reduce to flatten your array and then use Set to get distinct values and use array#from to get back array from Set.
var a = [1,2,3,4,5];
var b = [1,2,7,8];
var c = [1,2,3,4,5,6,7,8];
var d = [9,10,11,12];
var arr = [a,b,c,d]
var result = Array.from(new Set(arr.reduce((r,a) => r.concat(a))));
console.log(result);
Try using .filter when adding each array to the final one, filtering out the duplicates:
a.filter(function(item) {
return !finalArray.contains(item));
});
Answer using Sets:
var a = [1,2,3,4,5];
var b = [1,2,7,8];
var c = [1,2,3,4,5,6,7,8];
var d = [9,10,11,12];
var concat = a.concat(b).concat(c).concat(d);
var union = new Set(concat);
//console.log(union);
ES6 Answer:
let a = new Set([1,2,3,4,5]);
let b = new Set([1,2,7,8]);
let c = new Set([1,2,3,4,5,6,7,8]);
let d = new Set([9,10,11,12]);
let arr = new Set([...a,...b,...c,...d]);
//Result in arr.
Whats going on???
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set:
The Set object lets you store unique values of any type, whether
primitive values or object references.
So when we initialise Sets passing arrays to the constructor we basically ensure that there are no duplicate values.
Then in the last line, we concat all the Sets we initialised prior into a final set.
The ... notation converts the Set into an array, and when we pass the 4 arrays to the constructor of the Set they get concatenated and a Set of their unique values is created.
Here is a functional alternative written in ES5.
var flatten = function(list) {
return list.reduce(function(acc, next) {
return acc.concat(Array.isArray(next) ? flatten(next) : next);
}, []);
};
var unique = function(list) {
return list.filter(function(element, index) {
return list.indexOf(element) === index;
})
}
var a = [1,2,3,4,5];
var b = [1,2,7,8];
var c = [1,2,3,4,5,6,7,8];
var d = [9,10,11,12];
var arr = [a,b,c,d];
var result = unique(flatten(arr));
console.log(result);
If you support ES6, arrow function can make that code even shorter.
Here is a solution that uses a plain object for resolving duplicates, and only uses basic ES3 JavaScript. Runs in IE 5.5 and higher, and with O(n) time complexity.
function uniques(arr) {
var obj = {}, result = [];
for (var i = 0; i < arr.length; i++) {
obj[arr[i]] = true;
}
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) result.push(+prop);
}
return result;
}
// Example use
var a = [1,2,3,4,5],
b = [1,2,7,8],
c = [1,2,3,4,5,6,7,8],
d = [9,10,11,12];
var result = uniques(a.concat(b, c, d));
console.log('Result: ' + result);
As an object can only have a unique set of properties (no duplicates), the use of all array values as properties in an object will give you an object with a property for each unique value. This happens in the first loop. NB: the value given to those properties is not relevant; I have used true.
Then the result is just the conversion of those properties back to array values. This happens in the second loop.
var a = [1,2,3,4,5];
var b = [1,2,7,8];
var c = [1,2,3,4,5,6,7,8];
var d = [9,10,11,12];
var result = a.concat(b,c,d);
function remvDup(result){
var tmp = [];
for(var i = 0; i < result.length; i++){
if(tmp.indexOf(result[i]) == -1){
tmp.push(result[i]);
}
}
return tmp;
}
console.log(remvDup(result));
Becuase the OP mentioned that he cannot use 'Set' as it is not supported on the targeted browsers, I would recommand using the 'union' function from the lodash library.
See union's documentation here

Pushing an Object to Array in js

I'm trying to push an Object to an Array using the following command:
a = a.concat(b);
a = [];
b = {a: Object1, b: Object2 ....};
So I wan to have array a to be like a = [Object1, Object2...]
But the above statement results in:
a = [[Object1, Object2...][Object11, Object12...]];
How can I achieve this in JS?
If I´m understanding what you want, you want just objects, not the keys. So, could be:
for( var key in b ){
var value = b[key];
a.push(value);
}
console.log(JSON.stringify(a));
Hope it helps...
You are concatenating two arrays with Array.concat() you need to use Array.push().
var a = [ObjectA];
var b = ObjectB;
a.push(b);
// a = [ObjectA, ObjectB];
let a = [];
let b = {a:1, b:2, c:3};
for(obj in b){
let val = {};
val[obj] = b[obj];
a.push(val);
}
console.log(a);
Did you mean something like this ?
The Object.values() method returns an array of a given object's own enumerable property values,
You could use the Object values method Object.values(), like :
Object.values(b);
Example :
var a = [];
var obj_1 = {'attr_1': 'val_1', 'attr_2': 'val_2'};
var obj_2 = {'attr_3': 'val_3', 'attr_4': 'val_4'};
var b = {'a': obj_1, 'b': obj_2};
a = Object.values(b);
console.log( a );
Hope this helps.

How to combine arrays in JavaScript? [duplicate]

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.

Javascript/Jquery- new array from existing two arrays

I have two arrays
var a= $("#update-select1").val(); // gives value 1,2,4
var b= $("#update-select2").val(); // 1,2,5
I want two different arrays from the above two arrays.
//array has the values which is in `b` but not in `a`
var c = [5]
//another array has value in `a` but not in `b`
var d =[4]
You can use Array.filter this way:
var c = [1,2,5]
.filter(function(a){return this.indexOf(a) === -1},[1,2,4]); //=> [5]
var d = [1,2,4]
.filter(function(a){return this.indexOf(a) === -1},[1,2,5]); //=> [4]
Or:
function notIn(a){
return this.indexOf(a) === -1;
}
var a = [1,2,4]
,b = [1,2,5]
,c = b.filter(notIn,a)
,d = a.filter(notIn,b);
See also
You can try the grep() method
var a1 = [1, 2, 4];
var a2 = [1, 2, 5];
var difference = $.grep(a1, function (x) {
return $.inArray(x, a2) < 0
});
alert(" the difference is " + difference);​
JSFiddle
I know this is an old question, but I thought I would share this
little trick.
var diff = $(old_array).not(new_array).get();
diff now contains what was in old_array that is not in new_array
Found this on Compare 2 arrays which returns difference
try something like this
var a= [1,2,4];
var b= [1,2,5];
var c = [];
jQuery.each(b,function(k,v){
if(a.indexOf(v) < 0){
c.push(v);
}
})
console.log(c);//[5]
var d = [];
jQuery.each(a,function(k,v){
if(b.indexOf(v) < 0){
d.push(v);
}
})
console.log(d);//[4]

Categories