How do you group an array via JavaScript [duplicate] - javascript

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 4 months ago.
How do I group the array via javascript to just
Vehicles
Food
I can't figure it out via "reduce" since the array has no "key" to specify.
Thank you

const group1 = arr.filter(item => item === 'Vehicles');
const group2 = arr.filter(item => item === 'Food');
Or if you want a general solution:
let groups = {};
for (const item of arr) {
if (!groups[item]) groups[item] = [];
groups[item].push(item);
}

I think I don't get your question completely, but if you are trying to remove duplicates, this could be an option
const originalArray = ["vehicle", "food", "vehicle", "food", "vehicle", "food"];
const noDuplicates = new Set(originalArray);
console.log(Array.from(noDuplicates));

Related

array.push() and splite in Array of arrays [duplicate]

This question already has answers here:
Split array into chunks
(73 answers)
Closed 6 days ago.
This post was edited and submitted for review 6 days ago.
I'm using arrayofArrays[0].push() inside a for loop in order to add an Object to the Array0 inside arrayofArrays.
Now I'd like that when Array0 has reached 2 element, the next element will be pushed to Array1, in order to achieve this situation:
var arrayofArrays = [[Obj0,Obj1],[Obj2,Obj3],[Obj4,Obj5], ...];
Sample code:
var arrayofArrays = [[]];
for(data in Data){
var Obj = {"field1":data[0], "field2":data[1], "field3":data[2] }
arrayofArrays[0].push(Obj); // need to pass to arrayofArrays[1] when arrayofArrays[0] has 2 Obj...
}
(I don't need to split an existing array, I'm adding Object to an array, and want them to split in sub-arrays while adding them)
Here is a functional programming approach to your question to unflatten an array:
const arr = Array.from(Array(6).keys()); // [0, 1, 2, 3...]
let t;
let arrOfArr = arr.map((v, idx) => {
if(idx % 2) {
return [t, v];
} else {
t = v;
return null;
}
}).filter(Boolean);
console.log({
arr,
arrOfArr,
});
Note: Array.from(Array(6).keys()) is just for demo. Replace this with any array of objects you like

Create a array of objects by grouping objects conditionally [duplicate]

This question already has answers here:
Group array items using object
(19 answers)
How can I group an array of objects by key?
(32 answers)
Closed last month.
I am trying to create a new array of objects by comparing two arrays.One array contains the ids to be compared and the other contains the dataset which should be compared with the first array are a new array of object must be created.
Let me explain this in detail
Consider array 1:
['1','2']
Array 2
[{name:'Linus',id:'1'},{name:'Anthony',id:'1'},{name:'Jake',id:'2'},{name:'Eva',id:'2'}]
What I am expecting as a output is:
[
{id:'1',users:[{name:'Linus',id:'1'},{name:'Anthony',id:'1'}]},
{id:'2',users:[{name:'Jake',id:'2'},{name:'Eva',id:'2'}
]
I am not sure what has to be done.
Something like this for example
const ids = ['1','2'];
const users = [{name:Linus,id:'1'},{name:Anthony,id:'1'},{name:Jake,id:'2'},{name:Eva,id:'2'}];
const groups = ids.map(id =>{
return {
id,
users: users.filter(u => u.id === id)
}
})
const groupBy = ['1','2'];
const data = [{name:'Linus',id:'1'},{name:'Anthony',id:'1'},{name:'Jake',id:'2'},{name:'Eva',id:'2'}];
const result = groupBy.map(id => {
return {
id,
users: data.filter(item => item.id == id),
}
})
console.log(result);
Try this code

Combine Arrays in JavaScript Without Duplicates [duplicate]

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 5 months ago.
I need to combine ccAddresses and toAddresses values into just one set of array without duplication.
Expected Output
{ "newAddresses": ["john#gmail.com", "joshua#gmail.com", "jane#gmail.com", "james#gmail.com"] }
const old = [
{
"ccAddresses": ["john#gmail.com", "joshua#gmail.com"],
},
{
"ccAddresses": ["jane#gmail.com", "joshua#gmail.com"],
"toAddresses": ["jane#gmail.com", "james#gmail.com"],
}
];
const news = old.flatMap((val, index) => ({
"newAddress": val.ccAddresses
}))
console.log(news)
const res = Array.from(new Set([...old.flatMap(x => [...x.ccAddresses])]))
UPDATED(as per new author's requirement):
Array.from(new Set([...old.flatMap(x => [...x.ccAddresses].concat([...x.toAddresses || []]))]))

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)

How to merge two arrays to make an object [duplicate]

This question already has answers here:
Create an object from an array of keys and an array of values
(9 answers)
Closed 1 year ago.
consider i have an array say
let arr1=["john","Bruce","Clent"];
and
let arr2=[55,33,22];
Then how can i make an object out of this in javascript
object should look like:{"john":55,"Bruce":33,"Clent":22};
it should take arr1 as object's keys and arr2 as object'values
You can just loop the array, but use the index to match the key and value.
const arr1=["john","Bruce","Clent"];
const arr2=[55,33,22];
const obj = {};
arr1.forEach((val, i) => {
obj[val] = arr2[i];
});

Categories

Resources