How to apply function against an accumulator and each key of object in JavaScript ?
In this article, we will see how to apply a function against an accumulator and each key in the object in JavaScript. Accumulators can be functions, objects, arrays, etc. In this article, we use the accumulator and key of an object against the function.
Approach: In our approach, we use to reduce. First, we get the keys from the object and make a function. After getting keys, we use reduce for apply function against a collection of keys and accumulator. In the reducing method, we use accumulator and key as arguments of the callback function which is our function.
Syntax:
Collection.reduce((accumulator, key)=>
function(accumulator,key), InitialValue);
Example 1:
Javascript
<script>
function ApplyingFn() {
function function (robj, key) {
var l1 = 'Below 30000' ;
var l2 = 'Below 40000' ;
var l3 = 'Below 50000' ;
var l4 = 'Above 50000' ;
if (m[key] < 30000) {
robj[l1].push(key);
}
if (m[key] < 40000) {
robj[l2].push(key)
}
if (m[key] < 50000) {
robj[l3].push(key)
}
else {
robj[l4].push(key)
}
return robj;
}
var k = {
'Below 30000' : [], 'Below 40000' : [],
'Below 50000' : [], 'Above 50000' : []
};
var m = {
'Rahul' : 15000, 'Shyam' : 220000,
'David' : 420000, 'Sam' : 35000, 'Ram' : 450000
};
var l = Object.keys(m).reduce((accumulator,
key) => function (accumulator, key), k);
console.log(l);
}
ApplyingFn();
</script>
|
Output:
{'Below 30000': ['Rahul'],
'Below 40000': ['Rahul', 'Sam'],
'Below 50000': ['Rahul', 'Sam'],
'Above 50000': ['Shyam', 'David','Ram']}
Example 2:
Javascript
<script>
function ApplyingFn() {
function function (robj, value, key) {
if (robj[value] == undefined) {
robj[value] = [];
robj[value].push(key);
}
else {
robj[value].push(key)
}
return robj;
}
var m = {
'Ms.Dhoni' : 'Cricket' ,
'Sunil Chhetri' : 'Football' ,
'Rishabh Pant' : 'Cricket' ,
'K.L Rahul' : 'Cricket' ,
'Ishan Pandita' : 'Football' ,
};
var l = Object.keys(m).reduce((accumulator,
key) => function (accumulator, m[key], key), {});
console.log(l);
}
ApplyingFn();
</script>
|
Output:
{'Cricket': ['Ms.Dhoni', 'Rishabh Pant', 'K.L Rahul'],
'Football': ['Sunil Chhetri', 'Ishan Pandita']}
Last Updated :
10 Feb, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...