Create a zipmap function using javascript? - javascript

Consider this problem:
Create a function zipmap that takes in two sequences, and creates a dictionary from the elements of the first sequence to the elements of the second.
zipmap([1, 2, 3], [4, 5, 6]) => {1: 4, 2: 5, 3: 6}
My solution is below as an answer, can anyone come up with a better way of doing it?

This is already built into Ramda, as zipObj:
console .log (
R.zipObj ([1, 2, 3], [4, 5, 6])
)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>
And it's also now a language feature, maybe not yet quite widely enough supported, but getting close: Object.fromEntries.

const zipmap = (arr1 ,arr2) => arr1.reduce((p,c,i) => {
p[c] = arr2[i];
return p;
},{});

Here's a simple recursive implementation -
// None : symbol
const None =
Symbol()
// zipMap : ('k array, 'v array) -> ('k, 'v) object
const zipMap = ([ k = None, ...keys ] = [], [ v = None, ...values ] = []) =>
k === None || v === None
? {}
: { [k]: v, ...zipMap(keys, values) }
console.log(zipMap([ 1, 2, 3 ], [ 4, 5, 6 ]))
// { 1: 4, 2: 5, 3: 6 }
But it's not much of a "mapping" function; it always returns an Object. What if you wanted a different result?
// None : symbol
const None =
Symbol()
// identity : 'a -> 'a
const identity = x =>
x
// zipMap : (('k, 'v) -> ('kk, 'vv), 'k array, 'v array) -> ('kk, 'vv) array
const zipMap =
( f = identity // ('k, v') -> ('kk, 'vv)
, [ k = None, ...keys ] = [] // 'k array
, [ v = None, ...values ] = [] // 'v array
) => // ('kk, 'vv) array
k === None || v === None
? []
: [ f ([ k, v ]), ...zipMap(f, keys, values) ]
// result : (number, number) array
const result =
zipMap
( identity
, [ 1, 2, 3 ]
, [ 4, 5, 6 ]
)
console.log(result)
// [ [ 1, 4 ], [ 2, 5 ], [ 3, 6 ] ]
console.log(Object.fromEntries(result))
// { 1: 4, 2: 5, 3: 6 }
// result2 : (number, number) array
const result2 =
zipMap
( ([ k, v ]) => [ k * 10, v * 100 ]
, [ 1, 2, 3 ]
, [ 4, 5, 6 ]
)
console.log(Object.fromEntries(result2))
// { 10: 400, 20: 500, 30: 600 }
Instead of creating an Object using Object.fromEntries, you could just as easily create a Map too -
// result2 : (number, number) array
const result2 =
zipMap
( ([ k, v ]) => [ k * 10, v * 100 ]
, [ 1, 2, 3 ]
, [ 4, 5, 6 ]
)
// m : (number, number) map
const m =
new Map(result2)
// Map { 10 => 400, 20 => 500, 30 => 600 }

const R = require('ramda')
const zipmapSeparate = (...arr) => arr[0].map((zeroEntry, index) => {
const item = {}
item[arr[0][index]] = arr[1][index]
return item
})
const zipmapReduce = (zipmap1) => zipmap1.reduce((accumulator, current) => {
const key = Object.keys(current)[0]
const value = Object.values(current)[0]
accumulator[key]=value
return accumulator
}, {})
const zipmap = R.compose(zipmapReduce, zipmapSeparate)
console.log(zipmap([1, 2, 3], [4, 5, 6]))

Related

how to get the number of pair values in array? Javascript

I am trying this solution but it is not giving me the result I want.
I don't want to count the number of pairs of 1 cause it is not really a pair as it appears 4 times.
I need to count the "perfect" pairs, like in this case: 5 and 2. Right now this is giving me 4 as result and it should be 2.
How could I achieve that? I am stuck.
let ar1 = [12, 5, 5, 2, 1, 1, 1, 1, 2];
const countPairs = (ar) => {
let obj = {};
ar.forEach((item) => {
obj[item] = obj[item] ? obj[item] + 1 : 1;
});
return Object.values(obj).reduce((acc, curr) => {
acc += Math.floor(curr / 2);
return acc;
}, 0);
};
console.log( countPairs(ar1) )
You can filter the object values by 2 and count the list
let ar1 = [12, 5, 5, 2, 1, 1, 1, 1, 2];
const countPairs = (ar) => {
let obj = {};
ar.forEach((item) => {
obj[item] = obj[item] ? obj[item] + 1 : 1;
});
return Object.values(obj).filter(e => e == 2).length;
};
console.log(countPairs(ar1))
This can be one-liner using Map as:
const countPairs(arr) => [...arr.reduce((dict, n) => dict.set(n, (dict.get(n) ?? 0) + 1), new Map()).values(),].filter((n) => n === 2).length;
let ar1 = [12, 5, 5, 2, 1, 1, 1, 1, 2];
const countPairs = (arr) =>
[
...arr
.reduce((dict, n) => dict.set(n, (dict.get(n) ?? 0) + 1), new Map())
.values(),
].filter((n) => n === 2).length;
console.log(countPairs(ar1));
or that
const
ar1 = [12, 5, 5, 2, 1, 1, 1, 1, 2]
, countPerfectPairs = arr => arr.reduce((r,val,i,{[i+1]:next})=>
{
if(!r.counts[val])
{
r.counts[val] = arr.filter(x=>x===val).length
if (r.counts[val]===2) r.pairs++
}
return next ? r : r.pairs
},{counts:{},pairs:0})
console.log( countPerfectPairs(ar1) )
If you prefer Details:
const
ar1 = [12, 5, 5, 2, 1, 1, 1, 1, 2]
, countPerfectPairs = arr => arr.reduce((r,val)=>
{
if(!r.counts[val])
{
r.counts[val] = arr.filter(x=>x===val).length
if (r.counts[val]===2) r.pairs++
}
return r
},{counts:{},pairs:0})
console.log( countPerfectPairs(ar1) )

Flatten JavaScript nested object

I have a nested object look like this:
let obj = {
F:{
asian: {
"35-44": 1,
"55-": 1,
},
"asian/black": {
"0-24": 1,
"35-44": 1,
"45-54": 2,
},
},
M:{
asian: {
"35-44": 1,
"55-": 1,
},
white: {
"0-24": 1,
"35-44": 1,
"45-54": 2,
},
},
}
And I want to flatten the object to this:
res = {
F: 6,
M: 6,
asian: 4,
"asian/black": 4,
white: 4,
"0-24": 2,
"35-44": 4,
"45-54": 4,
"55-": 2,
}
That every value in res should be the sum of the deepest object values(F, M) and object values with the same key(0-24, 35-44...). I feel this can be done using recursion and just can't get it right. The code I write:
let returnVal = 0
const flatten = (obj, prefix = '', res = {}) => {
return Object.entries(obj).reduce((r, [key, val]) => {
if(typeof val === 'object'){
flatten(val, key, r)
} else {
res[key] = val
returnVal = val;
}
if (key in res) {
res[key] += returnVal
} else {
res[key] = 0
res[key] += returnVal
}
return r
}, res)
}
console.log(flatten(obj))
it will output:
result = {
"0-24": 2,
"35-44": 2,
"45-54": 4,
"55-": 2,
F: 2,
M: 2,
asian: 2,
"asian/black": 2,
white: 2,
}
F, M, and some other keys are not correct. Thanks!
Another, perhaps simpler, approach is as follows:
const consolidate = (obj, path = [], results = {}) =>
Object .entries (obj) .reduce ((results, [k, v]) =>
Object (v) === v
? consolidate (v, [...path, k], results)
: [...path, k] .reduce (
(results, n) => ({...results, [n] : (results[n] || 0) + v}),
results
),
results)
const data = {F: {asian: {"35-44": 1, "55-": 1}, "asian/black": {"0-24": 1, "35-44": 1, "45-54": 2}}, M: {asian: {"35-44": 1, "55-": 1}, white: {"0-24": 1, "35-44": 1, "45-54": 2}}}
console .log (consolidate (data))
.as-console-wrapper {min-height: 100% !important; top: 0}
We recursively track paths taken through the object, such as ['F', 'asian/black', '45-54'] or ['M', 'white'] or simply ['f'] as well as an object containing the final results. When we the value at the current node is an object, we recur, adding the current property name to the path. When it's not (for this data it must therefore hit a number), we hit a base case in which we take each node in the current path, and update the results object by adding that number to the value for the node in the results object, or setting it to the current value if that value doesn't exist.
There is a potential issue with the default parameters, as described in another Q & A. If someone tried to map the consolidate function directly over an array of input objects, it would fail. If this is a concern, it's easy enough to swap the default parameters for a wrapper function:
const _consolidate = (obj, path, results) =>
Object .entries (obj) .reduce ((results, [k, v]) =>
Object (v) === v
? _consolidate (v, [...path, k], results)
: [...path, k] .reduce (
(results, n) => ({...results, [n] : (results[n] || 0) + v}),
results
),
results)
const consolidate = (obj) =>
_consolidate (obj, [], {})
const data = {
F: {
asian: {
"35-44": 1,
"55-": 1,
},
"asian/black": {
"0-24": 1,
"35-44": 1,
"45-54": 2,
},
},
M: {
asian: {
"35-44": 1,
"55-": 1,
},
white: {
"0-24": 1,
"35-44": 1,
"45-54": 2,
},
},
};
const isObject = obj => Object.prototype.toString.call(obj) === "[object Object]";
function nestKeys(obj, parent = "") {
return Object.keys(obj).map(key => {
const k = parent.length ? [parent, key].join(".") : key;
if (!isObject(obj[key])) {
return k;
}
return nestKeys(obj[key], k);
}).flat();
}
function flatObj(obj) {
const map = {};
const keys = nestKeys(obj);
keys.forEach(nestedKey => {
const splited = nestedKey.split(".");
const val = splited.reduce((acc, cur) => acc[cur], obj);
splited.forEach(k => {
map[k] = (map[k] || 0) + val;
})
});
return map;
}
console.log(flatObj(data));

Key value pair intersection of an array of objects

I would like to know if there is a way to find the intersection of a key value pair in an array of objects. Let's say you have an array of three objects which all have the same keys like this :
arrayOfObj = [
{
"a": 1,
"b": "stringB"
"c": {"c1":1,
"c2": "stringC2"
}
},
{
"a": 1,
"b": "stringBdiff"
"c": {"c1":1,
"c2": "stringC2"
}
},
{
"a": 1,
"b": "stringB"
"c": {"c1":1,
"c2": "stringC2"
}
}
]
I would like to find the common key value pairs of the three objects:
output= [
{"a":1},
{"c": {"c1":1,
"c2":"stringC2"
}
}
]
This is what I have done so far, it works but not on nested objects. I would like to know if there is a more elegant way to do it and one that could work on nested object as well.
let properties;
let commonFound = false;
let notCommonFound = false;
const commonValues = [];
let value;
const initialArray = [{
"a": 2,
"b": "stringB",
"c": {
"c1": 1,
"c2": "stringC2"
}
},
{
"a": 1,
"b": "stringB",
"c": {
"c1": 2,
"c2": "stringC2"
}
},
{
"a": 1,
"b": "stringB",
"c": {
"c1": 2,
"c2": "stringC2"
}
}
];
const commonStorage = [];
const reference = initialArray[0];
properties = Object.keys(reference);
properties.forEach((property) => {
for (let i = 0; i < initialArray.length; i++) {
commonFound = false;
notCommonFound = false;
for (let j = 0; j <i ; j++) {
if (initialArray[i][property] === initialArray[j][property]) {
commonFound = true;
value = initialArray[i][property];
}
else {
notCommonFound = true;
value = [];
}
}
}
if (commonFound && !notCommonFound) {
commonStorage.push({[property] : value});
}
});
console.log(commonStorage);
Before we implement intersect we'll first look at how we expect it to behave –
console.log
( intersect
( { a: 1, b: 2, d: 4 }
, { a: 1, c: 3, d: 5 }
)
// { a: 1 }
, intersect
( [ 1, 2, 3, 4, 6, 7 ]
, [ 1, 2, 3, 5, 6 ]
)
// [ 1, 2, 3, <1 empty item>, 6 ]
, intersect
( [ { a: 1 }, { a: 2 }, { a: 4, b: 5 }, ]
, [ { a: 1 }, { a: 3 }, { a: 4, b: 6 }, ]
)
// [ { a: 1 }, <1 empty item>, { a: 4 } ]
, intersect
( { a: { b: { c: { d: [ 1, 2 ] } } } }
, { a: { b: { c: { d: [ 1, 2, 3 ] } } } }
)
// { a: { b: { c: { d: [ 1, 2 ] } } } }
)
Challenging problems like this one are made easier by breaking them down into smaller parts. To implement intersect we will plan to merge two calls to intersect1, each contributing one side of the computed result –
const intersect = (left = {}, right = {}) =>
merge
( intersect1 (left, right)
, intersect1 (right, left)
)
Implementing intersect1 is remains relatively complex due to the need to support both objects and arrays – the sequence of map, filter, and reduce helps maintain a flow of the program
const intersect1 = (left = {}, right = {}) =>
Object.entries (left)
.map
( ([ k, v ]) =>
// both values are objects
isObject (v) && isObject (right[k])
? [ k, intersect (v, right[k]) ]
// both values are "equal"
: v === right[k]
? [ k, v ]
// otherwise
: [ k, {} ]
)
.filter
( ([ k, v ]) =>
isObject (v)
? Object.keys (v) .length > 0
: true
)
.reduce
( assign
, isArray (left) && isArray (right) ? [] : {}
)
Lastly we implement merge the same way we did in the other Q&A –
const merge = (left = {}, right = {}) =>
Object.entries (right)
.map
( ([ k, v ]) =>
isObject (v) && isObject (left [k])
? [ k, merge (left [k], v) ]
: [ k, v ]
)
.reduce (assign, left)
The final dependencies –
const isObject = x =>
Object (x) === x
const isArray =
Array.isArray
const assign = (o, [ k, v ]) =>
(o [k] = v, o)
Verify the complete program works in your browser below –
const isObject = x =>
Object (x) === x
const isArray =
Array.isArray
const assign = (o, [ k, v ]) =>
(o [k] = v, o)
const merge = (left = {}, right = {}) =>
Object.entries (right)
.map
( ([ k, v ]) =>
isObject (v) && isObject (left [k])
? [ k, merge (left [k], v) ]
: [ k, v ]
)
.reduce (assign, left)
const intersect = (left = {}, right = {}) =>
merge
( intersect1 (left, right)
, intersect1 (right, left)
)
const intersect1 = (left = {}, right = {}) =>
Object.entries (left)
.map
( ([ k, v ]) =>
isObject (v) && isObject (right[k])
? [ k, intersect (v, right[k]) ]
: v === right[k]
? [ k, v ]
: [ k, {} ]
)
.filter
( ([ k, v ]) =>
isObject (v)
? Object.keys (v) .length > 0
: true
)
.reduce
( assign
, isArray (left) && isArray (right) ? [] : {}
)
console.log
( intersect
( { a: 1, b: 2, d: 4 }
, { a: 1, c: 3, d: 5 }
)
// { a: 1 }
, intersect
( [ 1, 2, 3, 4, 6, 7 ]
, [ 1, 2, 3, 5, 6 ]
)
// [ 1, 2, 3, <1 empty item>, 6 ]
, intersect
( [ { a: 1 }, { a: 2 }, { a: 4, b: 5 }, ]
, [ { a: 1 }, { a: 3 }, { a: 4, b: 6 }, ]
)
// [ { a: 1 }, <1 empty item>, { a: 4 } ]
, intersect
( { a: { b: { c: { d: [ 1, 2 ] } } } }
, { a: { b: { c: { d: [ 1, 2, 3 ] } } } }
)
// { a: { b: { c: { d: [ 1, 2 ] } } } }
)
intersectAll
Above intersect only accepts two inputs and in your question you want to compute the intersect of 2+ objects. We implement intersectAll as follows -
const None =
Symbol ()
const intersectAll = (x = None, ...xs) =>
x === None
? {}
: xs .reduce (intersect, x)
console.log
( intersectAll
( { a: 1, b: 2, c: { d: 3, e: 4 } }
, { a: 1, b: 9, c: { d: 3, e: 4 } }
, { a: 1, b: 2, c: { d: 3, e: 5 } }
)
// { a: 1, c: { d: 3 } }
, intersectAll
( { a: 1 }
, { b: 2 }
, { c: 3 }
)
// {}
, intersectAll
()
// {}
)
Verify the results in your browser –
const isObject = x =>
Object (x) === x
const isArray =
Array.isArray
const assign = (o, [ k, v ]) =>
(o [k] = v, o)
const merge = (left = {}, right = {}) =>
Object.entries (right)
.map
( ([ k, v ]) =>
isObject (v) && isObject (left [k])
? [ k, merge (left [k], v) ]
: [ k, v ]
)
.reduce (assign, left)
const intersect = (left = {}, right = {}) =>
merge
( intersect1 (left, right)
, intersect1 (right, left)
)
const intersect1 = (left = {}, right = {}) =>
Object.entries (left)
.map
( ([ k, v ]) =>
isObject (v) && isObject (right[k])
? [ k, intersect (v, right[k]) ]
: v === right[k]
? [ k, v ]
: [ k, {} ]
)
.filter
( ([ k, v ]) =>
isObject (v)
? Object.keys (v) .length > 0
: true
)
.reduce
( assign
, isArray (left) && isArray (right) ? [] : {}
)
const None =
Symbol ()
const intersectAll = (x = None, ...xs) =>
x === None
? {}
: xs .reduce (intersect, x)
console.log
( intersectAll
( { a: 1, b: 2, c: { d: 3, e: 4 } }
, { a: 1, b: 9, c: { d: 3, e: 4 } }
, { a: 1, b: 2, c: { d: 3, e: 5 } }
)
// { a: 1, c: { d: 3 } }
, intersectAll
( { a: 1 }
, { b: 2 }
, { c: 3 }
)
// {}
, intersectAll
()
// {}
)
remarks
You'll want to consider some things like –
intersect
( { a: someFunc, b: x => x * 2, c: /foo/, d: 1 }
, { a: someFunc, b: x => x * 3, c: /foo/, d: 1 }
)
// { d: 1 } (actual)
// { a: someFunc, c: /foo/, d: 1 } (expected)
We're testing for what's considered equal here in intersect1 –
const intersect1 = (left = {}, right = {}) =>
Object.entries (left)
.map
( ([ k, v ]) =>
isObject (v) && isObject (right[k])
? [ k, intersect (v, right[k]) ]
: v === right[k] // <-- equality?
? [ k, v ]
: [ k, {} ]
)
.filter
( ...
If we want to support things like checking for equality of Functions, RegExps, or other objects, this is where we would make the necessary modifications
recursive diff
In this related Q&A we compute the recursive diff of two objects

Averaging out corresponding index value of arrays considering their lengths

I have a multidimensional array which contains arrays of different lengths.
I want to average the corresponding index values of all the arrays.
For arrays that don't have the index won't be considered when averaging the values.
var multiArray = [
[4, 1, 3],
[6, 4, 2, 3, 4],
[8, 6, 1, 2],
[2, 3]
];
var avgIdxArray = [];
// logic helper
// (4 + 6 + 8 + 2) / 4 = 5
// (1 + 4 + 6 + 3) / 4 = 3.5
// (3+ 2 +1) / 3 = 2
// (3 + 2) / 5 = 2.5
// 4 / 1 = 4;
// (sum of index values) / number of arrays that have those index
// desired output
console.log(avgIdxArray);
// [5, 3.5 ,2 ,2.5 ,4]
Can it be achieved using the .map(), .filter() and .reduce() method? Also what could be the most efficient way of handling this problem?
One solution is this:
1- Convert multiArray array to its vertical type (New array with their indexes as you said in question)
2- Calculate sum and then avg of each array.
var multiArray = [
[4, 1, 3],
[6, 4, 2, 3, 4],
[8, 6, 1, 2],
[2, 3]
],
target = [];
multiArray.map((itm) => {
let x = Object.keys(itm);
x.forEach((ii) => {
if (target.length <= ii) {
target.push([]);
}
target[ii].push(itm[ii])
});
});
target.forEach((arr)=> {
let sum = arr.reduce(function(a, b) { return a + b; });
let avg = sum / arr.length;
console.log(avg)
})
Iterate the array with Array.reduce(). Iterate the sub array with Array.forEach(), and collect the sum, and the amount of items in the index. Use Array.map() to convert each sum/count object to average:
const multiArray = [
[4, 1, 3],
[6, 4, 2, 3, 4],
[8, 6, 1, 2],
[2, 3]
];
const result = multiArray
.reduce((r, a) => {
a.forEach((n, i) => {
const { sum = 0, count = 0 } = r[i] || {};
r[i] = { sum: sum + n, count: count + 1 };
});
return r;
}, [])
.map(({ sum, count }) => sum / count);
console.log(result);
Pure mapreduce.
Object.keys(multiArray.sort( (x,y) => y.length - x.length)[0]).
map( x => Object.keys(multiArray).
map(y => x < multiArray[y].length?multiArray[y][x]:undefined)).
map( a => ({sum: (a.reduce((l,r) => (l?l:0) + (r?r:0))), length: (a.filter(x => x).length)}) ).
map( pair => pair.sum / pair.length)
Output
[ 5, 3.5, 2, 2.5, 4 ]
A lot going there. Lets take it step by step
var multiArray = [
... [4, 1, 3],
... [6, 4, 2, 3, 4],
... [8, 6, 1, 2],
... [2, 3]
... ];
Order the arrays so that the array with the most element becomes first
multiArray.sort( (x,y) => y.length - x.length)
[ [ 6, 4, 2, 3, 4 ], [ 8, 6, 1, 2 ], [ 4, 1, 3 ], [ 2, 3 ] ]
Take the first element and loop over its keys. This is the largest element as we have sorted it before.
Object.keys(multiArray.sort( (x,y) => y.length - x.length)[0])
[ '0', '1', '2', '3', '4' ]
Now check if all the arrays have that key, else put an undefined over there
Object.keys(multiArray.sort( (x,y) => y.length - x.length)[0]).
map( x => Object.keys(multiArray).
map(y => x < multiArray[y].length?multiArray[y][x]:undefined)).
[ [ 6, 8, 4, 2 ],
[ 4, 6, 1, 3 ],
[ 2, 1, 3, undefined ],
[ 3, 2, undefined, undefined ],
[ 4, undefined, undefined, undefined ] ]
Create an object with sum and length. This part is optional, but I wanted this to be clear
Object.keys(multiArray.sort( (x,y) => y.length - x.length)[0]).
map( x => Object.keys(multiArray).
map(y => x < multiArray[y].length?multiArray[y][x]:undefined)).
map( a => ({sum: (a.reduce((l,r) => (l?l:0) + (r?r:0))), length: (a.filter(x => x).length)}) )
[ { sum: 20, length: 4 },
{ sum: 14, length: 4 },
{ sum: 6, length: 3 },
{ sum: 5, length: 2 },
{ sum: 4, length: 1 } ]
Finally get the avg
Object.keys(multiArray.sort( (x,y) => y.length - x.length)[0]).
map( x => Object.keys(multiArray).
map(y => x < multiArray[y].length?multiArray[y][x]:undefined)).
map( a => ({sum: (a.reduce((l,r) => (l?l:0) + (r?r:0))), length: (a.filter(x => x).length)}) ).
map( pair => pair.sum / pair.length)
[ 5, 3.5, 2, 2.5, 4 ]

make function take multiple variables from an array passed in as parameter

How to make function take multiple variables from an array passed in as parameter?
Edited
For example:
Achieve this:
const inputObj = [
['Anna', 10, 'Monday'],
['Anna', 15, 'Wednesday'],
['Beatrice', 8, 'Monday'],
['Beatrice', 11, 'Wednesday'],
['Anna', 4, 'Wednesday'],
['Beatrice', 5, 'Monday'],
['Beatrice', 16, 'Monday']
]
// expected output:
const outputObj = [
[ 'Anna', 10, 'Monday' ],
[ 'Anna', 19, 'Wednesday' ],
[ 'Beatrice', 29, 'Monday' ],
[ 'Beatrice', 11, 'Wednesday' ]
]
const arr = [0, 2]
const someFunction = (obj, v, a) => {
const result = obj.reduce((acc, cur) => {
const key = `${cur[a[0]]}|${cur[a[1]]}`
if(!acc[key]) acc[key] = cur
else acc[key][1] += cur[v]
return acc
}, {})
return Object.values(result)
}
console.log(someFunction(inputObj, 1, arr))
with this:
const arr = [0, 2, 3, ...] // basically the array could contain any number of items.
const someFunction = (obj, v, objParams) => {
const result = obj.reduce((acc, cur) => {
const key = ???
...
}, {})
}
So that the function can be reused and it accepts custom-sized arrays, check if the column numbers in the array are the same, then adds the sum of the column that is passed in as v?
How to declare the variables from the objParams to achieve the same result as the code above does?
Also how to add v in the middle of cur?
Assuming objParams is an array of unknown size (strings in this example):
const objParams = ["c1", "c2", "c3"];
const key = objParams.join(']}|${cur[');
const built = '${cur[' + key + ']';
Built is:
${cur[c1]}|${cur[c2]}|${cur[c3]
With ES6 you can use the spread operator in the argument definition.
More reading about spread operator on MDN
function sum(...args) {
return args.reduce((result, value) => result + value, 0)
}
const numbers = [1, 2, 3];
console.log('sum', sum(2, 2));
console.log('sum', sum(...numbers));
console.log('sum', sum(1, 2, 1, ...numbers));
// get single args before accumulating the rest
function sum2(foo, bar, ...args) {
return args.reduce((result, value) => result + value, 0)
}
console.log('sum2', sum2(2, 2));
console.log('sum2', sum2(...numbers));
console.log('sum2', sum2(1, 2, 1, ...numbers));

Categories

Resources