JavaScript array manipulation interview question [duplicate] - javascript

This question already has answers here:
Merge objects with same id in array
(7 answers)
Closed 1 year ago.
This is a question that I have encountered during an interview:
Write a function to transform the array:
[
{name:'a',values:[1,2]},
{name:'b',values:[3]},
{name:'a',values:[4,5]}
]
to:
[
{name:'a',values:[1,2,4,5]},
{name:'b',values:[3]}
]
I know this is not hard, but I just can't figure it out.
Does anyone know how to solve it?
Are there any places that I can find and practice more practical questions like this one?

You can group the array by name and then get an array using the grouped object:
const bla = [
{name:'a',values:[1,2]},
{name:'b',values:[3]},
{name:'a',values:[4,5]}
];
const res = Object.values(bla.reduce((obj, { name, values }) => {
obj[name] = obj[name] ?? {name, values: []}
obj[name].values.push(...values)
return obj
}, {}));
console.log(res)

Related

How to get last objects from an array of the identical objects?(JavaScript) [duplicate]

This question already has an answer here:
How to get the last occurrence of the duplicated array in Javascript
(1 answer)
Closed 3 months ago.
How can I get the last object from an array of identical objects. I attached the code. I will appreciate any help. Thank you!
Input
[
{name:'Sam', count:3},
{name:'Sam', count:5},
{name:'Sam', count:8},
{name:'Jill', count:7},
{name:'Jill', count:6},
]
Output
[
{name:'Sam', count:8},
{name:'Jill', count:6},
]
You can use reduce() to do it, each time we check if the name exists or not,if it exists then remove the exists one and put the new one into the result array
Update: Based on #Simon's comment,I update my answer with more simple code
let data = [
{name:'Sam', count:3},
{name:'Sam', count:5},
{name:'Sam', count:8},
{name:'Jill', count:7},
{name:'Jill', count:6},
]
let result = Object.values(data.reduce((a,c) => {
a[c.name] = c
return a
},{}))
console.log(result)

SUM AND GROUPING JSON DATA USING JAVASCRIPT [duplicate]

This question already has answers here:
How to group by and sum an array of objects? [duplicate]
(2 answers)
Sum JavaScript object propertyA values with the same object propertyB in an array of objects
(12 answers)
Group by, and sum, and generate an object for each array in JavaScript
(4 answers)
ES6 Implementation of Group By and SUM
(4 answers)
Javascript array of objects group and sum items
(4 answers)
Closed last year.
Sorry if this has been asked before, but I couldn't find a good example of what I'm trying to accomplish. Maybe I'm just not searching for the right thing. Please correct me if there's an explanation of this somewhere.
so let's says I have a data like this :
data = [
{"no":1,"location":"New York","transaction":3000},
{"no":2,"location":"Tokyo","transaction":3000},
{"no":3,"location":"New York","transaction":3000},
{"no":4,"location":"Amsterdam","transaction":3000},
{"no":5,"location":"Manchester","transaction":3000},
{"no":6,"location":"New York","transaction":3000},
{"no":7,"location":"Tokyo","transaction":3000},
{"no":8,"location":"Tokyo","transaction":3000},
{"no":9,"location":"New York","transaction":3000},
{"no":10,"location":"Amsterdam","transaction":3000}
]
what i wanted to is an output like this :
result = [
{"location":"New York","transaction":12000},
{"location":"Tokyo","transaction":9000},
{"location":"Amsterdam","transaction":6000}
{"location":"Manchester","transaction":3000}
]
so what i wanted to do is grouping the data based on location and sum the transaction where the location is same and push the data to another array. i don't know where to start, need some help to solve this or any suggestion to solve this using Javascript. thank you
Working Demo :
// Input array
const data = [
{"no":1,"location":"New York","transaction":3000},
{"no":2,"location":"Tokyo","transaction":3000},
{"no":3,"location":"New York","transaction":3000},
{"no":4,"location":"Amsterdam","transaction":3000},
{"no":5,"location":"Manchester","transaction":3000},
{"no":6,"location":"New York","transaction":3000},
{"no":7,"location":"Tokyo","transaction":3000},
{"no":8,"location":"Tokyo","transaction":3000},
{"no":9,"location":"New York","transaction":3000},
{"no":10,"location":"Amsterdam","transaction":3000}
];
// result array
const resultArr = [];
// grouping by location and resulting with an object using Array.reduce() method
const groupByLocation = data.reduce((group, item) => {
const { location } = item;
group[location] = group[location] ?? [];
group[location].push(item.transaction);
return group;
}, {});
// Finally calculating the sum based on the location array we have.
Object.keys(groupByLocation).forEach((item) => {
groupByLocation[item] = groupByLocation[item].reduce((a, b) => a + b);
resultArr.push({
'location': item,
'transaction': groupByLocation[item]
})
})
console.log(resultArr)

Converting a dynamic array into single object [duplicate]

This question already has answers here:
How do I convert array of Objects into one Object in JavaScript?
(17 answers)
Closed 2 years ago.
I have a dynamic array which is like this.
var callData = [
{
"FIELD_1": "0763454333"
},
{
"FIELD_2": "dgfdgfg"
},
{
"FIELD_3": "fgfdgfdg"
}
];
According to the user, these number of fields changes. If another user has more fields, there can be FIELD_4, FIELD_5 and so on. I fetch these data from db and put it into and array as above. Now I want to convert it a single object. I want it to look like this.
{
"FIELD_1": "076355998", "FIELD_2": "933504395v", "FIELD_3": "123"
}
Although I found converting solutions in stackoverflow, Those didn't solve my problem. How can I achieve this? Please guide.
use flatMap function to return entries of each object and then use Object.fromEntries function to create an object from the entries
var callData = [
{"FIELD_1": "0763454333" },
{ "FIELD_2": "dgfdgfg" },
{ "FIELD_3": "fgfdgfdg" }
];
const res = Object.fromEntries(callData.flatMap(o => Object.entries(o)));
console.log(res);

Javascript to Group Array of Object into combination of two values [duplicate]

This question already has answers here:
How can I group an array of objects by key?
(32 answers)
Create Multilevel groups from an Array of Objects
(2 answers)
Closed 4 years ago.
var data=[
{custType:1,code:'savings',efDate:'2/3/19',exDate'2/3/19'},
{custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:1,code:'current',efDate:'2/3/19',exDate:'2/3/19'},
{custType:2,code:'current',efDate:'2/3/19',exDate:'2/3/19'},
{custType:2,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:2,code:'savings',efDate:'2/3/19',exDate:'2/3/19'}
];
expected results
var modifiedData=[
[
savings=[ {custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'}
],
current=[ {custType:1,code:'current',efDate:'2/3/19',exDate:'2/3/19'} ]
],
[
savings=[ {custType:2,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:2,code:'savings',efDate:'2/3/19',exDate:'2/3/19'} ],
current=[ {custType:2,code:'current',efDate:'2/3/19',exDate:'2/3/19'} ]
]
];
as i am trying to find a group with (custType and code), i am not able to generate the expected result. Which method i should use here? can i use reduce or groupBy. I am confused about it.
You could build up a nested hashtable:
const hash = {};
for(const value of data) {
const group = hash[value.custType] || (hash[value.custType] = {});
const group2 = group[value.code] || (group[value.code] = []);
group2.push(value);
}
const result = Object.values(hash).map(Object.values);

Sort array of array on string value in Javascript [duplicate]

This question already has answers here:
Sort array of objects by string property value
(57 answers)
Closed 6 years ago.
I want to sort the array of array on length of string, as follows
var arr = [
[1951, "Mayfer"],
[1785, "Actinac Capsules"],
[1007, "Ferri Injection"],
[1101, "Cetaphil"]
];
var sortedArr = sortOnLengthOfString(arr);
>> sortedArr = [
[1951, "Mayfer"],
[1101, "Cetaphil"],
[1007, "Ferri Injection"],
[1785, "Actinac Capsules"]
]
Is there a solution with lodash preferably? Or plain Javascript?
I haven't found duplicate question yet. Can someone find it? Please note, the sorting I am asking for, is for array of arrays and not array of objects.
You can use Array#sort at this context,
var obj = [
[1951, "Mayfer"],
[1785, "Actinac Capsules"],
[1007, "Ferri Injection"],
[1101, "Cetaphil"]
];
obj.sort(function(a,b){
return a[1].length - b[1].length
});
console.log(obj);
//[[1951, "Mayfer"],[1101, "Cetaphil"],[1007, "Ferri Injection"],[1785, "Actinac Capsules"]]

Categories

Resources