Sort object array based on another array of keys - javascript

I have two arrays containing objects. One contains keys in some order and another has data and I need to sort the data array in order against the given sorted key array. How can I do this?
var a = ['d','a','b','c'] ;
var b = [{a:1},{c:3},{d:4},{b:2}];
The result should be:
result = [{d:4},{a:1},{b:2},{c:3]

Try this
var a = ['d','a','b','c'] ;
var b = [{a:1},{c:3},{d:4},{b:2}];
b.sort(function(x,y){
var xkey = a.indexOf(Object.keys(x)[0]);
var ykey = a.indexOf(Object.keys(y)[0]);
return xkey - ykey;
})
document.body.innerHTML += JSON.stringify(b,0,4);

A different approach from above ones would be, using Lodash Javascript Library.
var a = ['d','a','b','c'] ;
var b = [{a:1},{c:3},{d:4},{b:2}];
var results = _.map(a,function(av) {
var obj = {};
obj[av] = _.find(b, av)[av];
return obj
});
document.body.innerHTML += JSON.stringify(results);
<script src="https://cdn.jsdelivr.net/lodash/4.11.1/lodash.min.js"></script>

This approach respects the keys in the objects of the array for sorting.
Only the items of a are used for lookup and their respective order.
In this case d gets all sort value of the item of b, so d looks like
[ 1, 3, 0, 2 ]
While sorting with indices, we need e, which has simply the indices of b
[ 0, 1, 2, 3 ]
after sorting it became
[ 2, 0, 3, 1 ]
the wanted sort order. Now the original array is remapped to the new order.
But why?
Usually objects contains more than one property. If you use Object.keys and take just the first element, then you could go wrong, because this element is not the wanted element for getting the sort order.
To make it save, you need a different approach, which does not use Array#indexOf in combination with a fixed item of Object.keys.
var a = ['d', 'a', 'b', 'c'],
b = [{ a: 1 }, { c: 3 }, { d: 4 }, { b: 2 }],
d = b.map(function (bb) {
var k = -1;
a.some(function (aa, i) {
if (aa in bb) {
k = i;
return true;
}
});
return k;
}),
e = b.map(function (_, i) { return i; });
e.sort(function (a, b) {
return d[a] - d[b];
});
b = e.map(function (a) {
return b[a];
});
document.write('<pre> ' + JSON.stringify(b, 0, 4) + '</pre>');

This should do the trick
result = a.map(function(key) {
for(var i=0; i<b.length; ++i) {
if(key in b[i]) return b[i];
}
});

Brute force approach is to loop through each of a array and check the b array for it's presence.
var a = ['d','a','b','c'] ;
var b = [{a:1},{c:3},{d:4},{b:2}];
var ans = [];
for(var i = 0; i < a.length; ++i)
{
for(var j = 0; j < b.length; ++j)
{
if(b[j][a[i]])
ans.push(b[j]);
}
}
document.write(JSON.stringify(ans, 0, 4));

Related

Modify an object to a new Array in Javascript

sorry, i m a beginner in javascript.
Can someone explain me how to modify this Object
{toto:[12,13,15],titi:[45,12,34]}
to this Array
newArray = [
{
toto:12,
titi:45
},{
toto:13,
titi:12
},{
toto:15,
titi:34}
]
Also, what the solution if the toto and titi doesn't have the same lenght
Thanks for support!
Here's how I did it. In this way, you don't need to know the names of the keys or the size of the array, but it does require a few loops.
obj = {toto:[12,13,15],titi:[45,12,34]};
newArray = [];
// Find the longest array in your data set
longest = 0;
Object.keys(obj).forEach(function(key) {
if (obj[key].length > longest) {
longest = obj[key].length;
}
});
// Loop through the existing data set to create new objects
for (i = 0; i<longest; i++) {
newObject = {};
Object.keys(obj).forEach(function(key) {
newObject[key] = obj[key][i];
});
newArray.push(newObject);
}
console.log(newArray);
plnkr.co demo in the script.js file.
If you want to ignore keys that would have undefined values for uneven loops, you can add a conditional inside the forEach loop that creates a new object:
Object.keys(obj).forEach(function(key) {
if (obj[key][i] !== undefined) {
newObject[key] = obj[key][i];
}
});
Assuming lengths of toto and titi are the same:
Obj = {toto:[12,13,15],titi:[45,12,34]};
newArray = [];
for (var k in Obj["toto"]) {
newArray.push({ toto:Obj["toto"][k],titi:Obj["titi"][k] });
}
Since the lengths of your inner arrays are equal, you should be able to simply loop through them and add a value from each array (for each iteration) into a new array :
// Your input
var input = {toto:[12,13,15],titi:[45,12,34]};
// An array to store your output
var output = [];
// Since your inner arrays are of equal size, you can loop through them
// as follows
for(var i = 0; i < input.toto.length; i++){
output.push({ toto: input.toto[i], titi: input.titi[i]});
}
You can see a working example of this here and what the output array looks like below :
A more generic approach
var object = { toto: [12, 13, 15], titi: [45, 12, 34] },
newArray = function (o) {
var keys = Object.keys(o),
l = keys.reduce(function (r, a) { return Math.max(r, o[a].length); }, 0),
i = 0,
t,
result = [];
while (i < l) {
t = {};
keys.forEach(function (k) { t[k] = o[k][i]; });
result.push(t);
i++;
}
return result;
}(object);
document.write('<pre>' + JSON.stringify(newArray, 0, 4) + '</pre>');

Group array values that are in the same range of multiples of 10

I have an array, for example:
var arr = [2,4,7,11,25,608,65,109,99,100,504,606,607];
I need to make it so each value that is within range of its multiple of ten below and and multiple of ten above it is grouped together.
For example, 2,4,7 are between 0 and 10 so they must be together.
11 would be alone in its group, like 25,65 etc.
606,607,608 would be together.
The array above should become:
[ [2,4,7],[11],[25],[65],[99],[101],[504],[100,109],[606,607,608] ]
I've been thinking about it for a couple of hours and I wasn't able to come up with anything yet. It's really bad not much worth mentioning but so far I'm playing with Math.round (http://jsfiddle.net/40napnyx/2/)
Edit:
I'd like to add another issue (although I will not pick the correct answer based on this if the actual answers don't include the solution of this new problem).
The array may contain values with letters. Those values should all be in the same group, in alphabetical order (only the first letter is taken to determine the order). This group should be the last value in the resulting array.
So for instance
var arr = [2, 4, 11,'a3', 25, 7, 'j', 'bzy4];
Would be [[2,4,7],[11],[25],['a3','bzy4', 'j']]
Here's a generic function:
function groupBy(ary, keyFunc) {
var r = {};
ary.forEach(function(x) {
var y = keyFunc(x);
r[y] = (r[y] || []).concat(x);
});
return Object.keys(r).map(function(y) {
return r[y];
});
}
// usage:
var arr = [2,4,7,11,25,608,65,99,101,504,606,607];
g = groupBy(arr, function(x) { return Math.floor(x / 10) });
document.write(JSON.stringify(g));
For your bonus question, just apply groupBy twice:
function groupBy(ary, keyFunc) {
var r = {};
ary.forEach(function(x) {
var y = keyFunc(x);
r[y] = (r[y] || []).concat(x);
});
return Object.keys(r).map(function(y) {
return r[y];
});
}
var arr = [2, 4, 11,'a3', 25, 7, 'j', 'bzy4'];
g = groupBy(arr, isNaN);
g = [].concat(
groupBy(g[0], function(x) { return Math.floor(x / 10) }),
[g[1].sort()]
);
document.write(JSON.stringify(g));
This is what I came up with:
var arr = [2,4,7,11,25,65,99,101,504,606,607,608];
arr.sort(function(a, b) {
if(a > b) return 1;
if(a < b) return -1;
else return 0;
});
var grouped_array = [];
for(var i = 0; i < arr.length; i++) {
var group = [];
var curr_group = Math.floor(arr[i]/10);
while(Math.floor(arr[i]/10) == curr_group) {
group.push(arr[i]);
i++;
}
grouped_array.push(group);
}
http://jsfiddle.net/40napnyx/3/

Sorting an array according to another array's sorted index

I have two arrays. I should do a normal sort on one (descending or ascending) and sort the other according to how the first array is sorted. This is because each element in the first array has a relationship with the same index element on the second array, and I must keep this relationship true. For example:
sortThis=[3,1,2];
sortAccording=["With 3","With 1","With 2];
I couldn't find any way to take the index changes from JavaScript's sort function.
Solution:
To achieve that, you have to zip both arrays in just one. This is, given you have this two array:
sortThis=[3,1,2];
sortAccording=["With 3","With 1","With 2];
After zip them, you will have the following array:
zipped = [{a: 3, b: "With 3"}, {a: 1, b: "With 1"}, {a: 2, b: "With 2"}];
Then, you sort it by a in order to have:
zippedAndSorted = [{a: 1, b: "With 1"}, {a: 2, b: "With 2"}, {a: 3, b: "With 3"}];
What next?
Well, once you have this array sorted by what you want, you have to extract their values with the map function and finnaly you will have your two arrays sorted by the same criteria:
The code:
// your arrays
sortThis=[3,1,2];
sortAccording=["With 3","With 1","With 2"];
// the zip function
function zip(a,b) {
return a.map(function(aa, i){ return { i: aa, j: b[i]};} )
};
// ziping and sorting the arrays
var zipped = zip(sortThis, sortAccording);
zippedAndSorted = zipped.sort(function(a,b){ return a.i - b.i; });
// your two sorted arrays
sortedThis = zippedAndSorted.map(function(a){ return a.i;});
sortedAccording = zippedAndSorted.map(function(a){ return a.j;});
You also can see it working here: http://jsfiddle.net/lontivero/cfpcJ/
Good luck!
For example:
function zip(a, b) {
var i = 0, j = 0, r = [];
while(i < a.length && j < b.length)
r.push([a[i++], b[j++]]);
return r;
}
function unzip(r) {
var a = [], b = [];
for(var i = 0; i < r.length; i++) {
a.push(r[i][0]);
b.push(r[i][1]);
}
return [a, b];
}
r = zip(sortAccording, sortThis);
r.sort();
r = unzip(r);
sortAccording = r[0]
sortThis = r[1]
Another way:
result = sortAccording.
map(function(elem, pos) { return [elem, pos]}).
sort().
map(function(elem) { return sortThis[elem[1]]})
Better implementations of zip and unzip (both working with variable number of arguments):
zip = function() {
var args = [].slice.call(arguments, 0);
return args[0].map(function(_, i) {
return args.map(function(a) {
return a[i]
})
})
}
unzip = function(a) {
return a[0].map(function(_, i) {
return a.reduce(function(y, e) {
return y.concat(e[i])
}, [])
})
}
I have a simple solution to this. Create a third array of indexes. Just sort that index array based on the sort of first array.
var indexArray = [];
for (var i=0; i < sortThis.length; i++) {
indexArray[i] = i;
}
indexArray.sort(function(a, b) {
return (sortThis[a] > sortThis[b]) ? 1 : (sortThis[a] === sortThis[b]) ? 0 : -1;
});
// Now you have the sorted index ready
console.log("The first elements in the arrays are: " + sortThis(indexArray[0]) + " and " + sortAccording(indexArray[0]));

Shuffling array properties in JavaScript

I have a data dictionary like this:
var data = {
'text1': 1,
'text2': 2,
'text3': 3,
...
'text20': 20
];
I need to pick a random selection of those keys and then shuffle it's values. In the example, it should write something like this:
> console.log(choose(data, 5));
[ { key: 'text15', value: 8 },
{ key: 'text6', value: 3 },
{ key: 'text3', value: 15 },
{ key: 'text19', value: 6 },
{ key: 'text8', value: 19 } ]
For now I'm extracting the keys into another array and sorting by Math.random() but I'm stuck at swaping the values because no key should have the same value it initially had.
How would you swap key/values here?
Thanks
I put together a possible solution using underscore.js to simplify traversing the object and arrays in a cross browser manner:
var data = {
text1: 1,
text2: 2,
text3: 3,
text4: 4,
text5: 5,
text6: 6,
text7: 7,
text8: 8,
text9: 9,
text10: 10
};
function choose(data, num)
{
var keys = _.sortBy(
_.keys(data),
function(k)
{
return (Math.random() * 3) - 1;
}
),
results = [],
k1, k2;
if (num > keys.length) {
throw new Error('Impossible to retrieve more values than exist');
}
while (results.length < num) {
k1 = k2 || keys.pop();
k2 = keys.pop();
results.push({key:k1, value: data[k2]});
}
return results;
}
console.log(choose(data, 5));
This isn't necessarily an optimal approach but it seems to meet your requirements. I first grab all of the keys and sort them randomly. I then loop through the random keys creating a new object with one key and the following keys value. That way you'll always end up with a different value associated with each key. If you need it to work when the value of num passed in to the function == the number of keys in the data then you'll have to add a little more code - I'll leave that as an exercise for the reader :)
You can have a play with this code on jsfiddle:
http://jsfiddle.net/zVyQW/1/
You could do this:
collect names and corresponding values in two arrays names and values
shuffle both arrays independently of each other
take the first n items of both arrays and combine them
Here’s an example implementation:
Array.prototype.shuffle = function() {
for (var i=this.length-1, j, tmp; i>0; i--) {
j = Math.round(Math.random()*i);
tmp = this[i], this[i] = this[j], this[j] = tmp;
}
return this;
};
function choose(data, number) {
var names = [], values = [], pick = [];
for (var name in data) {
if (data.hasOwnProperty(name)) {
names.push(name);
values.push(data[name]);
}
}
names = names.shuffle(), values = values.shuffle();
for (var i=Math.min(number >>> 0, names.length-1); i>=0; i--) {
pick.push({key: names[i], value: values[i]});
}
return pick;
}
Been a while since this was answered, but I was working on shuffling and found the following to be by far the fastest implementation with an evenly random distribution.
It's fast because it only makes one call to Math.random on each iteration, all the rest is done by property access. It doesn't modify the array, just reassigns values.
function shuffle(a) {
var t, j, i=a.length, rand=Math.random;
// For each element in the array, swap it with a random
// element (which might be itself)
while (i--) {
k = rand()*(i+1)|0;
t = a[k];
a[k]=a[i];
a[i]=t;
}
return a;
}
It uses a combination of three functions (including the Array shuffle prototype method).
Here is the complete code:
var obj = {
"red":"RED",
"blue":"BLUE",
"green":"GREEN",
"yellow":"YELLOW",
"purple":"PURPLE"
};
Array.prototype.shuffle = function(){
for (var i = 0; i < this.length; i++){
var a = this[i];
var b = Math.floor(Math.random() * this.length);
this[i] = this[b];
this[b] = a;
}
}
obj = shuffleProperties(obj); // run shuffle
function shuffleProperties(obj) {
var new_obj = {};
var keys = getKeys(obj);
keys.shuffle();
for (var key in keys){
if (key == "shuffle") continue; // skip our prototype method
new_obj[keys[key]] = obj[keys[key]];
}
return new_obj;
}
function getKeys(obj){
var arr = new Array();
for (var key in obj)
arr.push(key);
return arr;
}
for(key in obj){
alert(key);
}
Check all post,
Best Regards.
Use an implementation of random that randomizes a discrete set of values, such as Math.rand seen here. For each index, randomize Math.rand(index, length-1) to get a list of random indexes, the location off all indices will change.

Getting a union of two arrays in JavaScript [duplicate]

This question already has answers here:
How to merge two arrays in JavaScript and de-duplicate items
(89 answers)
Closed 4 years ago.
Say I have an array of [34, 35, 45, 48, 49] and another array of [48, 55]. How can I get a resulting array of [34, 35, 45, 48, 49, 55]?
With the arrival of ES6 with sets and splat operator (at the time of being works only in Firefox, check compatibility table), you can write the following cryptic one liner:
var a = [34, 35, 45, 48, 49];
var b = [48, 55];
var union = [...new Set([...a, ...b])];
console.log(union);
Little explanation about this line: [...a, ...b] concatenates two arrays, you can use a.concat(b) as well. new Set() create a set out of it and thus your union. And the last [...x] converts it back to an array.
If you don't need to keep the order, and consider 45 and "45" to be the same:
function union_arrays (x, y) {
var obj = {};
for (var i = x.length-1; i >= 0; -- i)
obj[x[i]] = x[i];
for (var i = y.length-1; i >= 0; -- i)
obj[y[i]] = y[i];
var res = []
for (var k in obj) {
if (obj.hasOwnProperty(k)) // <-- optional
res.push(obj[k]);
}
return res;
}
console.log(union_arrays([34,35,45,48,49], [44,55]));
If you use the library underscore you can write like this
var unionArr = _.union([34,35,45,48,49], [48,55]);
console.log(unionArr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
Ref: http://underscorejs.org/#union
I'm probably wasting time on a dead thread here. I just had to implement this and went looking to see if I was wasting my time.
I really like KennyTM's answer. That's just how I would attack the problem. Merge the keys into a hash to naturally eliminate duplicates and then extract the keys. If you actually have jQuery you can leverage its goodies to make this a 2 line problem and then roll it into an extension. The each() in jQuery will take care of not iterating over items where hasOwnProperty() is false.
jQuery.fn.extend({
union: function(array1, array2) {
var hash = {}, union = [];
$.each($.merge($.merge([], array1), array2), function (index, value) { hash[value] = value; });
$.each(hash, function (key, value) { union.push(key); } );
return union;
}
});
Note that both of the original arrays are left intact. Then you call it like this:
var union = $.union(array1, array2);
If you wants to concatenate two arrays without any duplicate value,Just try this
var a=[34, 35, 45, 48, 49];
var b=[48, 55];
var c=a.concat(b).sort();
var res=c.filter((value,pos) => {return c.indexOf(value) == pos;} );
function unique(arrayName)
{
var newArray=new Array();
label: for(var i=0; i<arrayName.length;i++ )
{
for(var j=0; j<newArray.length;j++ )
{
if(newArray[j]==arrayName[i])
continue label;
}
newArray[newArray.length] = arrayName[i];
}
return newArray;
}
var arr1 = new Array(0,2,4,4,4,4,4,5,5,6,6,6,7,7,8,9,5,1,2,3,0);
var arr2= new Array(3,5,8,1,2,32,1,2,1,2,4,7,8,9,1,2,1,2,3,4,5);
var union = unique(arr1.concat(arr2));
console.log(union);
Adapted from: https://stackoverflow.com/a/4026828/1830259
Array.prototype.union = function(a)
{
var r = this.slice(0);
a.forEach(function(i) { if (r.indexOf(i) < 0) r.push(i); });
return r;
};
Array.prototype.diff = function(a)
{
return this.filter(function(i) {return a.indexOf(i) < 0;});
};
var s1 = [1, 2, 3, 4];
var s2 = [3, 4, 5, 6];
console.log("s1: " + s1);
console.log("s2: " + s2);
console.log("s1.union(s2): " + s1.union(s2));
console.log("s2.union(s1): " + s2.union(s1));
console.log("s1.diff(s2): " + s1.diff(s2));
console.log("s2.diff(s1): " + s2.diff(s1));
// Output:
// s1: 1,2,3,4
// s2: 3,4,5,6
// s1.union(s2): 1,2,3,4,5,6
// s2.union(s1): 3,4,5,6,1,2
// s1.diff(s2): 1,2
// s2.diff(s1): 5,6
I like Peter Ajtai's concat-then-unique solution, but the code's not very clear. Here's a nicer alternative:
function unique(x) {
return x.filter(function(elem, index) { return x.indexOf(elem) === index; });
};
function union(x, y) {
return unique(x.concat(y));
};
Since indexOf returns the index of the first occurence, we check this against the current element's index (the second parameter to the filter predicate).
Shorter version of kennytm's answer:
function unionArrays(a, b) {
const cache = {};
a.forEach(item => cache[item] = item);
b.forEach(item => cache[item] = item);
return Object.keys(cache).map(key => cache[key]);
};
You can use a jQuery plugin: jQuery Array Utilities
For example the code below
$.union([1, 2, 2, 3], [2, 3, 4, 5, 5])
will return [1,2,3,4,5]
function unite(arr1, arr2, arr3) {
newArr=arr1.concat(arr2).concat(arr3);
a=newArr.filter(function(value){
return !arr1.some(function(value2){
return value == value2;
});
});
console.log(arr1.concat(a));
}//This is for Sorted union following the order :)
function unionArrays() {
var args = arguments,
l = args.length,
obj = {},
res = [],
i, j, k;
while (l--) {
k = args[l];
i = k.length;
while (i--) {
j = k[i];
if (!obj[j]) {
obj[j] = 1;
res.push(j);
}
}
}
return res;
}
var unionArr = unionArrays([34, 35, 45, 48, 49], [44, 55]);
console.log(unionArr);
Somewhat similar in approach to alejandro's method, but a little shorter and should work with any number of arrays.
function unionArray(arrayA, arrayB) {
var obj = {},
i = arrayA.length,
j = arrayB.length,
newArray = [];
while (i--) {
if (!(arrayA[i] in obj)) {
obj[arrayA[i]] = true;
newArray.push(arrayA[i]);
}
}
while (j--) {
if (!(arrayB[j] in obj)) {
obj[arrayB[j]] = true;
newArray.push(arrayB[j]);
}
}
return newArray;
}
var unionArr = unionArray([34, 35, 45, 48, 49], [44, 55]);
console.log(unionArr);
Faster
http://jsperf.com/union-array-faster
I would first concatenate the arrays, then I would return only the unique value.
You have to create your own function to return unique values. Since it is a useful function, you might as well add it in as a functionality of the Array.
In your case with arrays array1 and array2 it would look like this:
array1.concat(array2) - concatenate the two arrays
array1.concat(array2).unique() - return only the unique values. Here unique() is a method you added to the prototype for Array.
The whole thing would look like this:
Array.prototype.unique = function () {
var r = new Array();
o: for(var i = 0, n = this.length; i < n; i++)
{
for(var x = 0, y = r.length; x < y; x++)
{
if(r[x]==this[i])
{
continue o;
}
}
r[r.length] = this[i];
}
return r;
}
var array1 = [34,35,45,48,49];
var array2 = [34,35,45,48,49,55];
// concatenate the arrays then return only the unique values
console.log(array1.concat(array2).unique());
Just wrote before for the same reason (works with any amount of arrays):
/**
* Returns with the union of the given arrays.
*
* #param Any amount of arrays to be united.
* #returns {array} The union array.
*/
function uniteArrays()
{
var union = [];
for (var argumentIndex = 0; argumentIndex < arguments.length; argumentIndex++)
{
eachArgument = arguments[argumentIndex];
if (typeof eachArgument !== 'array')
{
eachArray = eachArgument;
for (var index = 0; index < eachArray.length; index++)
{
eachValue = eachArray[index];
if (arrayHasValue(union, eachValue) == false)
union.push(eachValue);
}
}
}
return union;
}
function arrayHasValue(array, value)
{ return array.indexOf(value) != -1; }
Simple way to deal with merging single array values.
var values[0] = {"id":1235,"name":"value 1"}
values[1] = {"id":4323,"name":"value 2"}
var object=null;
var first=values[0];
for (var i in values)
if(i>0)
object= $.merge(values[i],first)
You can try these:
function union(a, b) {
return a.concat(b).reduce(function(prev, cur) {
if (prev.indexOf(cur) === -1) prev.push(cur);
return prev;
}, []);
}
or
function union(a, b) {
return a.concat(b.filter(function(el) {
return a.indexOf(el) === -1;
}));
}
ES2015 version
Array.prototype.diff = function(a) {return this.filter(i => a.indexOf(i) < 0)};
Array.prototype.union = function(a) {return [...this.diff(a), ...a]}
If you want a custom equals function to match your elements, you can use this function in ES2015:
function unionEquals(left, right, equals){
return left.concat(right).reduce( (acc,element) => {
return acc.some(elt => equals(elt, element))? acc : acc.concat(element)
}, []);
}
It traverses the left+right array. Then for each element, will fill the accumulator if it does not find that element in the accumulator. At the end, there are no duplicate as specified by the equals function.
Pretty, but probably not very efficient with thousands of objects.
I think it would be simplest to create a new array, adding the unique values only as determined by indexOf.
This seems to me to be the most straightforward solution, though I don't know if it is the most efficient. Collation is not preserved.
var a = [34, 35, 45, 48, 49],
b = [48, 55];
var c = union(a, b);
function union(a, b) { // will work for n >= 2 inputs
var newArray = [];
//cycle through input arrays
for (var i = 0, l = arguments.length; i < l; i++) {
//cycle through each input arrays elements
var array = arguments[i];
for (var ii = 0, ll = array.length; ii < ll; ii++) {
var val = array[ii];
//only add elements to the new array if they are unique
if (newArray.indexOf(val) < 0) newArray.push(val);
}
}
return newArray;
}
[i for( i of new Set(array1.concat(array2)))]
Let me break this into parts for you
// This is a list by comprehension
// Store each result in an element of the array
[i
// will be placed in the variable "i", for each element of...
for( i of
// ... the Set which is made of...
new Set(
// ...the concatenation of both arrays
array1.concat(array2)
)
)
]
In other words, it first concatenates both and then it removes the duplicates (a Set, by definition cannot have duplicates)
Do note, though, that the order of the elements is not guaranteed, in this case.

Categories

Resources