How to enumare objects and total of them with the same key with another object in array js - javascript

I'm populing a pdf template with an array of employees, and now I need to count the number of employees working in a same department, I found a way to count the total of concurrences but I can't enumarate the employee working in the department and the total of them. Can you help me? Thanks!!!
For example, I have this array of objects
const employees = [
{
id: 1,
name: "john",
department: {
id: 1,
},
},
{
id: 1,
name: "Mike",
department: {
id: 3,
},
},
{
id: 1,
name: "Leona",
department: {
id: 1,
},
},
{
id: 1,
name: "Lara",
department: {
id: 1,
},
},
];
Result Expected:
const employees = [
{
id: 1,
name: "john",
department: {
id: 1,
},
totalForDeparments: "1/3",
},
{
id: 1,
name: "Mike",
department: {
id: 3,
},
totalForDeparments: "1/1",
},
{
id: 1,
name: "Leona",
department: {
id: 1,
},
totalForDeparments: "2/3",
},
{
id: 1,
name: "Lara",
department: {
id: 1,
},
totalForDeparments: "3/3",
},
];

First you group by the department.id - then you can iterate the original array adding the correct indexes.
const employees = [{id:1,name:"john",department:{id:1}},{id:1,name:"Mike",department:{id:3}},{id:1,name:"Leona",department:{id:1}},{id:1,name:"Lara",department:{id:1}},];
var grouped = employees.reduce(function(agg, item) {
agg[item.department.id] = agg[item.department.id] || {
count: 0,
current: 0
}
agg[item.department.id].count++;
return agg;
}, {});
employees.map(function(item) {
var data = grouped[item.department.id]
data.current++;
item.totalForDeparments = data.current + "/" + data.count
})
console.log(employees)
.as-console-wrapper {max-height: 100% !important}

Related

creating a new array from two arrays with a new attribute

I have two arrays. First array is an array of object with each object respresenting a vote for an item, the id represents the item that was voted.
The second array contains all the options for that poll.
I want to create a new array with each option from the poll options with a new attribute having the percentage of votes they got from the votes array.
This is the votes array.
votes = [{
vote_id: 1, person: {name: ‘alan’}
}, {
vote_id: 2, person: {name: ‘John’}
},{
vote_id: 1, person: {name: ‘khan’}
}, {
vote_id: 1, person: {name: ‘martin’}
},{
vote_id: 3, person: {name: ‘mike’}
}]
Options = [{
id: 1, title: ’sweet’}, {
id: 2: ’salty’}, {
id: 3, title: ’spicy’}, {
id: 4, title: ’bitter’}]
This is the new array that I want to create from the data available from the above two arrays
new array = [{
Id: 1, title: ’sugar’, percentage: 60%},
{Id: 2, title: ’salt’, percentage: 20% },
{id: 3, title: ’spice’, percentage: 20%},
{id: 4, title: ‘bitter’, percentage: 0%}]
Separate the problem into two parts:
get the counts,
map percentage.
const
votes = [{ vote_id: 1, person: { name: 'alan' } }, { vote_id: 2, person: { name: 'John' } }, { vote_id: 1, person: { name: 'khan' } }, { vote_id: 1, person: { name: 'martin' } }, { vote_id: 3, person: { name: 'mike' } }],
options = [{ id: 1, title: 'sweet' }, { id: 2, title: 'salty' }, { id: 3, title: 'spicy' }, { id: 4, title: 'bitter' }],
counts = votes.reduce((r, { vote_id }) => {
r[vote_id] = (r[vote_id] || 0) + 1;
return r;
}, {}),
result = options.map(o => ({ ...o, percentage: ((counts[o.id] || 0) * 100 / votes.length).toString() + ' %' }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

search an item in multidimentionnal array

I'm trying to find an element on a multidimentionnal array usin JAVASCRIPT function, but I get error
This is my array's data:
export const datas = [
{
id: 1,
firstName: 'John',
tables: [
{ ID: 11, title: 'Lorem' },
{ ID: 12, title: 'Ipsum' },
],
},
{
id: 2,
firstName: 'Doe',
tables: [
{
ID: 22,
title: 'Arke',
nodes: [{ name: 'Name1' }, { name: 'Name2' }, { name: 'Name3' }],
},
{ ID: 23, title: 'Korem' },
],
},
{
id: 3,
firstName: 'Brad',
tables: [
{
ID: 30,
title: 'Mern',
nodes: [{ name: 'Name4' }, { name: 'Name5' }, { name: 'Name6' }],
},
{
ID: 31,
title: 'Full',
nodes: [{ name: 'Name7' }, { name: 'Name8' }, { name: 'Name9' }],
},
],
},
];
I've tried a reccursive function but it's not work, this is my code :
export const findById = (arr, id) => {
for (let o of arr) {
if (o.tables.length > 0) {
let a = findById(o.tables.nodes, 'id');
console.log(a);
}
}
};
I want to print the Object with ID 22, the problem is that I don't have the same structure in each dimension, and it still confuse me..
My Input : 22
My output :
{
ID: 22,
title: 'Arke',
nodes: [{ name: 'Name1' }, { name: 'Name2' }, { name: 'Name3' }],
},
Have you an idea how to edit my function to get my input's response ?
Your recursive function wasn't too far off, you need to check if the item as a tables first before recursively calling it again. And then finally just check the ID in the loop.
eg..
const datas=[{id:1,firstName:"John",tables:[{ID:11,title:"Lorem"},{ID:12,title:"Ipsum"}]},{id:2,firstName:"Doe",tables:[{ID:22,title:"Arke",nodes:[{name:"Name1"},{name:"Name2"},{name:"Name3"}]},{ID:23,title:"Korem"}]},{id:3,firstName:"Brad",tables:[{ID:30,title:"Mern",nodes:[{name:"Name4"},{name:"Name5"},{name:"Name6"}]},{ID:31,title:"Full",nodes:[{name:"Name7"},{name:"Name8"},{name:"Name9"}]}]}];
function findById(arr, ID) {
for (const a of arr) {
if (a.tables) {
const r = findById(a.tables, ID);
if (r) return r;
}
if (a.ID === ID) return a;
}
}
console.log(findById(datas, 22));
if you just need the nested data you can use flatMap and find
const findById = (arr, id) =>
arr
.flatMap(d => d.tables)
.find(t => t.ID === id)
const datas = [{
id: 1,
firstName: 'John',
tables: [{
ID: 11,
title: 'Lorem'
},
{
ID: 12,
title: 'Ipsum'
},
],
},
{
id: 2,
firstName: 'Doe',
tables: [{
ID: 22,
title: 'Arke',
nodes: [{
name: 'Name1'
}, {
name: 'Name2'
}, {
name: 'Name3'
}],
},
{
ID: 23,
title: 'Korem'
},
],
},
{
id: 3,
firstName: 'Brad',
tables: [{
ID: 30,
title: 'Mern',
nodes: [{
name: 'Name4'
}, {
name: 'Name5'
}, {
name: 'Name6'
}],
},
{
ID: 31,
title: 'Full',
nodes: [{
name: 'Name7'
}, {
name: 'Name8'
}, {
name: 'Name9'
}],
},
],
},
];
console.log(findById(datas, 22))
js has amazing array options https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
the ones which will help you most are probably:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap
here are some examples
// get the base with id 22
const baseWith22ID = datas.filter(f => f.tables.filter(s => s.id = 22))
// (i guess you want this one) get all elements with id 22
const onlyElementsWith22ID = datas.flatMap(f => f.tables.filter(s => s.id = 22))

How to Structure This array, Separate Category and Product

I have single array, I want to separate category and category Product
const product = [{
id: 1,
name: 'Cloth',
cat: ['fashion', 'man', 'women']
}, {
id: 2,
name: 'Shoes',
cat: ['fashion']
}, {
id: 3,
name: "hat",
cat: ['man', 'fashion']
}]
How to Separate category value from Product array.
const cat = ['fashion','man','women']
How to Separate category and Product
const result = [{
cat: 'fashion',
[{
id: 1,
name: 'Cloth'
}, {
id: 2,
name: 'Shoes'
}, {
id: 3,
name: "hat"
}]
}, {
cat: 'man',
[{
id: 1,
name: 'Cloth'
}, {
d: 3,
name: "hat"
}]
}, {
cat: 'women',
[{
id: 1,
name: 'Cloth'
}]
}]
How to develop this type of array please help me. Any one know please help me, Advance tanks for reply
First answer:
let categories = [];
const product = [
{ id: 1, name: "Cloth", cat: ["fashion", "man", "women"] },
{ id: 2, name: "Shoes", cat: ["fashion"] },
{ id: 3, name: "hat", cat: ["man", "fashion"] }
];
product.forEach((p) => {
p.cat.forEach((cat) => {
if(!categories.includes(cat)) {
categories.push(cat)
}
})
})
console.log(categories) // ['fashion','man','women']
If you one to get All categories from product Array.
let allCategories = [];
product.forEach(p => {
allCategories.push(...p.cat);
});
allCategories = [...new Set(allCategories)];
For second question I will use the result of first question:
allCategories.forEach(categorie => {
result.push(
{
cat: categorie,
products : product.filter(p => {
if(p.cat.includes(categorie)) {
return {
id : p.id,
name : p.name
}
}
})
}
)
})

Merge Duplicate object in array

I have an array I need to merge duplicate values with the sum of amount.
What would be an efficient algorithm
var arr = [{
item: {
id: 1,
name: "Abc"
},
amount: 1
}, {
item: {
id: 1,
name: "Abc"
},
amount: 2
}, {
item: {
id: 2,
name: "Abc"
},
amount: 2
},{
item: {
id: 1,
name: "Abc"
},
amount: 2
}]
I need solution as
[{
item: {
id: 1,
name: "Abc"
},
amount: 5
}, {
item: {
id: 2,
name: "Abc"
},
] amount: 2
}]
simply use Object.values() with Array.reudce() to merge objects and then get the values:
var arr = [{ item: { id: 1, name: "Abc" }, amount: 1 }, { item: { id: 1, name: "Abc" }, amount: 2 }, { item: { id: 2, name: "Abc" }, amount: 2 },{ item: { id: 1, name: "Abc" }, amount: 2 }];
var result = Object.values(arr.reduce((a,curr)=>{
if(!a[curr.item.id])
a[curr.item.id] = Object.assign({},curr); // Object.assign() is used so that the original element(object) is not mutated.
else
a[curr.item.id].amount += curr.amount;
return a;
},{}));
console.log(result);
used map to catch em all :D
var arr = [{ item: { id: 1, name: "Abc" }, amount: 1 }, { item: { id: 1, name: "Abc" }, amount: 2 }, { item: { id: 2, name: "Abc" }, amount: 2 },{ item: { id: 1, name: "Abc" }, amount: 2 }];
var res = {};
arr.map((e) => {
if(!res[e.item.id]) res[e.item.id] = Object.assign({},e); // clone, credits to: #amrender singh
else res[e.item.id].amount += e.amount;
});
console.log(Object.values(res));

Grouping array by same property value, iterate over that array

I have the following array:
var results = [
{ group: 1,
department: 2,
total: 10 },
{ group: 1,
department: 2,
total: 25 },
{ group: 1,
department: 3,
total: 15 },
{ group: 1,
department: 3,
total: 5 },
{ group: 2,
department: 4,
total: 10},
{ group: 2,
department: 4,
total: 50 }
]
I need to arrange the array into a 2D nested array, where the sub arrays are Group 1 and Group 2. The sub arrays should also be parent arrays, whose children are ordered by Department, like so:
var results:[
{
group1:[
{
department2:[
{
group:1,
department:2,
total:10
},
{
group:1,
department:2,
total:25
},
{
group:1,
department:3,
total:15
}
]
},
{
department3:[
{
group:1,
department:3,
total:5
}
]
}
]
},
{
group2:[
{
department4:[
{
group:2,
department:4,
total:10
},
{
group:2,
department:4,
total:50
}
]
}
]
}
]
This is for a react component, where I need to print each one as a row, but add a total after all the department groups are done, and then one after each group, and then a total after everything.
Perhaps I´m over complicating it and there is a better way?
var results = [
{ group: 1,
department: 2,
total: 10 },
{ group: 1,
department: 2,
total: 25 },
{ group: 1,
department: 3,
total: 15 },
{ group: 1,
department: 3,
total: 5 },
{ group: 2,
department: 4,
total: 10},
{ group: 2,
department: 4,
total: 50 }
]
var nested_result = {}
results.forEach(obj => {
if(nested_result[obj.group] === undefined) {
nested_result[obj.group] = {};
}
if(nested_result[obj.group][obj.department] === undefined) {
nested_result[obj.group][obj.department] = [];
}
nested_result[obj.group][obj.department].push(obj);
})
console.log(nested_result);
var results = [
{ group: 1, department: 2, total: 10 },
{ group: 1, department: 2, total: 25 },
{ group: 1, department: 3, total: 15 },
{ group: 1, department: 3, total: 5 },
{ group: 2, department: 4, total: 10},
{ group: 2, department: 4, total: 50 }
]
var outObj = {};
var out = results.map(function(a) {
var groupName = 'group' + a.group;
typeof outObj[groupName] == 'undefined' && ( outObj[groupName] = {});
var depName = 'department' + a.department;
typeof outObj[groupName][depName] == 'undefined' && ( outObj[groupName][depName] = [] );
outObj[groupName][depName].push(a );
});
console.log( outObj );

Categories

Resources