How to merge arrays? - javascript

How to merge these two arrays using JavaScript:
[{"id1":"value1","id2":"value2"}]
[{"id3":"value3","id4":"value4"}]
Into this:
[{"id1":"value1","id2":"value2","id3":"value3","id4":"value4"}]

You can use a simple function.
Either by adding the key/values from b into a:
function merge(a, b) {
for (var p in b[0]) {
a[0][p] = b[0][p];
}
return a;
}
merge(a, b);
Or by using a native array function like reduce:
function merge2(a, b) {
return b.reduce(function (el) {
return el;
}, a);
}
console.log(merge2(a, b));
DEMO

Just use the built-in Javascript Array .concat() method.
http://www.w3schools.com/jsref/jsref_concat_array.asp
var a = ["id1","value1","id2","value2"]
var b = ["id3","value3","id4","value4"]
var c = a.concat(b)
//c is now ["id1","value1","id2","value2","id3","value3","id4","value4"]

Related

How to dynamically construct a function's arguments without eval?

Given this code:
var arr = ['one', 'two'];
var obj = {
func: function(a, b) {
console.log(a, b);
}
};
Is there a way to dynamically construct the function call passing the items in the array as arguments without using eval()? Basically, the equivalent of this:
eval('obj.func(' + arr.join(',') + ')');
You can spread the array into the argument list:
var arr = ['one', 'two'];
var obj = {
func: function(a, b) {
console.log(a, b);
}
};
obj.func(...arr);
Or, if the environment doesn't support spread, you can use apply, which allows you to call a function with the supplied array converted to parameters:
var arr = ['one', 'two'];
var obj = {
func: function(a, b) {
console.log(a, b);
}
};
obj.func.apply(undefined, arr);

how to call same function with different parameter in javascript?

function partialize(){
}
function calculation(a,b,c){
console.log(a*b/c);
return a*b/c;
}
var a = 10, b= 20, c= 5;
var partialize1 = partialize(calculation, a);
partialize1(b,c)
var partialize2 = partialize(calculation, a, b);
partialize2(c)
var partialize3 = partialize(calculation, a, b, c);
partialize3()
I need to write partialize function which give same output in all three condition.
I tried like that it work .but i used spread operator .can we do this without spread operator ?
function partialize(fn,...a) {
console.log(...a);
return function (...b) {
console.log(...b);
fn(...a,...b);
}
}
function calculation(a, b, c) {
console.log(a * b / c);
return a * b / c;
}
var a = 10, b = 20, c = 5;
var partialize1 = partialize(calculation, a);
partialize1(b, c)
var partialize2 = partialize(calculation, a, b);
partialize2(c)
var partialize3 = partialize(calculation, a, b, c);
partialize3()
can we do the same thing without spread operator ?
You can save the initial arguments that were passed and return a function that can be called with the rest of the arguments, then calling the original function with apply:
function partialize(fn) {
const initialArguments = Array.from(arguments).slice(1);
return function() {
const finalArguments = Array.from(arguments);
fn.apply(null, initialArguments.concat(finalArguments));
}
}
function calculation(a, b, c) {
console.log(a * b / c);
return a * b / c;
}
var a = 10,
b = 20,
c = 5;
var partialize1 = partialize(calculation, a);
partialize1(b, c)
var partialize2 = partialize(calculation, a, b);
partialize2(c)
var partialize3 = partialize(calculation, a, b, c);
partialize3()
If your code is currently working as is but you'd like to change it to not use the spread operator, you can use the arguments object instead.
arguments object:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
Also check out this stackoverflow question for some example code working with the arguments object if helpful. How can I convert the "arguments" object to an array in JavaScript?
user944513, to simulate an overload of methods in javascript, yo can use the arguments object, which comes by default in the functions. To explain you better, i've written a block of code. Hope this can help you:
function suma(a = 0){
let resultado = 0;
console.log(arguments.length);
for(let i = 0; i < arguments.length; i++)
{
if(typeof(arguments[i] == "number")){
resultado += arguments[i];
}
}
}
suma(1,2,3,4); // 10
suma(1,2) // 3

Cartesian product on multiple array of objects in javascript

I have been working on cartesian product for single elements and array of objects. For single array elements I have understood the solution but for array of objects I struggle to achieve.
For example input
cartesianProductOf([{col1:'A'}], [{col2:'B'},{col3:'C'}])
Output :
[{col1:'A',col2:'B'},{col1:'A',col3:'C'}]
Here is the function which I was working on
function cartesianProductOf() {
return Array.prototype.reduce.call(arguments, function(a, b) {
var ret = [];
debugger;
a.forEach(function(a) {
b.forEach(function(b) {
var r = a.concat([b])
ret.push(r);
});
});
return ret;
}, [[]]);
}
This function returning this result
[{col1:'A'},{col2:'B'}],[{col1:'A'},{col3:'C'}]
Need guidance.
Instead of using an array to push to, you want to merge the objects:
function cartesianProductOf() {
return Array.prototype.reduce.call(arguments, function(a, b) {
var ret = [];
a.forEach(function(a_el) {
b.forEach(function(b_el) {
ret.push(Object.assign({}, a_el, b_el));
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
});
});
return ret;
}, [{}]);
// ^^
}
If you don't want to use Object.assign or it's polyfill, the equivalent would be
var r = {};
for (var p in a_el)
r[p] = a_el[p];
for (var p in b_el)
r[p] = b_el[p];
ret.push(r);
Here's a solution using Ramda.js
const cartesianProduct = (...Xs) =>
R.reduce(
(Ys, X) =>
R.map(R.apply(R.append), R.xprod(X, Ys)),
[[]],
Xs
)
const cartesianProductOf = (...objs) =>
R.map(R.mergeAll, cartesianProduct(...objs))
console.log(
cartesianProductOf(
[{col1: 'A'}],[{col2: 'B'}, {col3: 'C'}],
)
)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

Performing Set calculations in javascript array

I have 2 arrays lets say:
A = [1,2,3,4,5] and B = [1,2,3,6,7]
and I'd like to perform the following 'set calculations':
C = (A ∩ B)
D = A - (A ∩ B)
E = B - (A ∩ B)
Essentially:
C = [1,2,3]
D = [4,5]
E = [6,7]
Is there a smart way to do this or am I going to have to cross check each array member with loops and ifs? I cannot use an external library (like math.js or w/e).
Thanks in advance.
filter() can at least hide the loops for you:
A = [1,2,3,4,5];
B = [1,2,3,6,7];
C = intersection(A, B);
D = arrayDiff(A, C);
E = arrayDiff(B, C);
console.log(JSON.stringify(C));
console.log(JSON.stringify(D));
console.log(JSON.stringify(E));
function intersection(a, b) {
return a.filter(
function(el) {
return b.indexOf(el) >= 0;
}
);
}
function arrayDiff(a, b) {
return a.filter(
function(el) {
return b.indexOf(el) < 0;
}
);
}
As of ES6, Javascript has an inbuilt set object, which offers neat ways to do the above operations.
var intersection = function(setA, setB){
return new Set([x for (x of setA) if (setB.has(x))]);
}
var difference = function(setA, setB){
return new Set([x for (x of setA) if (!setB.has(x))]);
}
A = new Set([1,2,3,4,5]);
B = new Set([1,2,3,6,7]);
// A ∩ B = ([1,2,3])
intersection(A, B);
// A \ B = ([4,5])
difference(A, B);
// B \ A = ([6,7])
difference(B, A);

Sorted a javascript array of objects by an object property

Hay, i have an array of objects and i need to sort them (either DESC or ASC) by a certain property of each object.
Here's the data
obj1 = new Object;
obj1.date = 1307010000;
obj2 = new Object;
obj2.date = 1306923600;
obj3 = new Object;
obj3.date = 1298974800;
obj4 = new Object;
obj4.date = 1306923600;
obj5 = new Object;
obj5.date = 1307096400;
data = [obj1,obj2,obj3,obj4,obj5];
Now, i want to order the data array so that the objects are in order by date.
Can someone help me with this?
Use the Array sort() method
data.sort(function(a, b){
return a.date - b.date;
});
try this:
data.sort(function(a,b){
return a.date - b.date; //to reverse b.date-a.date
});
This solution works with any type of data:
sort_array_by = function(field, reverse, pr){
reverse = (reverse) ? -1 : 1;
return function(a,b){
a = a[field];
b = b[field];
if (typeof(pr) != 'undefined'){
a = pr(a);
b = pr(b);
}
if (a<b) return reverse * -1;
if (a>b) return reverse * 1;
return 0;
}
}
Then, use it like this (reverse sort):
data.sort(sort_array_by('date', true, function(a){
return new Date(a);
}));
As another example, you can sort it by a property of type "integer":
data.sort(sort_array_by('my_int_property', true, function(a){
return parseInt(a);
}));
We have an application using Angular/TypeScript and found it slightly easier on the eyes using an arrow function. In our case, the following code is example of what we have:
data.sort((a, b) => a.SortOrder - b.SortOrder);
Not a huge change but this helps moreso when you have many objects to be sorted.
You can use a custom sort function:
function mySort(a,b) {
return (a.date - b.date);
}
data.sort(mySort);
This is an example of how i use sorting array of objects in ascending order here "array" is array of an object.copy paste in a script tag and understand working through console...
function OBJECT(){
this.PROPERTY1 =Math.floor(Math.random()*10+1) ;
}
OBJECT.prototype.getPROPERTY1=function (){
return(this.PROPERTY1);
}
OBJECT.prototype.setPROPERTY1=function (PROPERTY){
this.PROPERTY1=PROPERTY;
}
var array= new Array();
console.log("unsorted object")
for(var a=0;a<10;a++)
{
array.push(new OBJECT());
console.log(array[a].getPROPERTY1())
}
function sorting() {
for(var i in array){
array[i].setPROPERTY1((array[i].getPROPERTY1()*1))
//that is just for sorting an integer value escape this line if not an
//integer property
}
var arr=new(Array);
var temp1=new(Array);
for(var i in array){
temp1.push(array[i]);
}
var temporary=new(Array)
for(var i in array)
{
var temp = array[i].getPROPERTY1();
arr.push(temp);
}
arr.sort(function(a,b){return a-b});
//the argument above is very important
console.log(arr)
for(var i in arr){
for(var j in temp1)
if(arr[i]==temp1[j].getPROPERTY1())
break;
temporary.push(temp1[j])
temp1.splice(j,1)//just this statement works for me
}
array.length=0;
for(var i in temporary)
{
array.push(temporary[i])
}
}
sorting();
console.log("sorted object")
for(var a=0;a<10;a++)
{
console.log(array[a].getPROPERTY1())
}

Categories