getting sum of previous element from list VUEJS - javascript

I am trying to get sum of previous element and add this to the existing list.
This is my current list:
ongoing: [
{
id: 'id1',
name: 'clientName',
productionTime: 15,
},
{
id: 'id2',
name: 'client',
productionTime: '15'
}
],
this is the result I want to achieve:
ongoing: [
{
id: 'id1',
name: 'clientName',
productionTime: 15,
sumofprevious: 15
},
{
id: 'id2',
name: 'client',
productionTime: 15,
sumofprevious: 30 (note: this comes from 15 + 15)
}
],
I use vuejs 3 with Pinia.
I tried many codes/examples but this is the closest one but it doesn't work as I want it. It doesn't read productionTime from ongoing
const thisList = computed(() => {
let array = storeOrders.ongoing.productionTime,
sum = 0,
newarray = array.map(value => sum += value)
return console.log(newarray)
})

You can use computed property:
const { computed, reactive } = Vue
const app = Vue.createApp({
setup() {
let ongoing = reactive([{id: 'id1', name: 'clientName', productionTime: 15,}, {id: 'id2', name: 'client', productionTime: '15'}])
const res = computed(() => {
let sum = 0
return ongoing.map(o => {
sum += +o.productionTime
return {...o, sumofprevious: sum}
})
})
const add = () => {
ongoing.push({id: Math.floor(Date.now() / 1000), name: 'name', productionTime: Math.ceil(Math.random() * 20),})
}
return { ongoing, res, add };
},
})
app.mount('#demo')
<script src="https://unpkg.com/vue#3/dist/vue.global.prod.js"></script>
<div id="demo">
<button #click="add">add</button>
<br />
ongoing: {{ ongoing }}
<br /><br />
result: {{ res }}
</div>

I would try to compute this:
const ongoing = [
{
id: 'id1',
name: 'clientName',
productionTime: 15,
sumOfPrevious: 0,
},
{
id: 'id2',
name: 'client',
productionTime: 15,
}
];
const sumOfPrev = () => {
return ongoing.map((el, i) => {
if (i !== 0) {
el.sumOfPrevious = ongoing[i-1].productionTime + el.productionTime;
}
return el;
})
}
console.log(sumOfPrev());

Related

Being able to remove duplicate keys from an array of objects

I have a question about how I can delete the existing elements, for example, in my case "Tallas" is repeated, could you please help me? Thank you very much to those who are willing to help me to solve this problem
const data =
[ { atributos: { Tallas: [{ id: 0, name: 'XS' }, { id: 1, name: 'S' }] }}
, { atributos: { Calzado: [{ id: 0, name: '10' }, { id: 1, name: '9.5' }] }}
, { atributos: { Tallas: [{ id: 0, name: 'XS' }] }}
]
The idea is to have this json format with the last "Tallas" since it is the last one that I added through my dynamic form.
const expected =
[{ atributos: { Calzado: [{ id: 0, name: '10' }, { id: 1, name: '9.5' }] }}
, { atributos: { Tallas: [{ id: 0, name: 'XS' }] }}
]
How do I do this is there a way to do it, I've tried with filter plus the findindex but I can't get to eliminate the repetition of the json res= new.filter((arr, index, self) => index === self.findIndex( (t) => (t.attributes === arr.attributes )))
To unique the array of objects, we can use the Javascript Set module, if the array has complex nested objects, we can stringify each object before creating new Set data. this below function will unique the array of complex objects.
function unique_array(array = []) {
const newSetData = new Set(array.map((e) => JSON.stringify(e)));
return Array.from(newSetData).map((e) => JSON.parse(e));
}
this is a function that takes an array and return the same array but delete every duplicated item
function removeDuplicates(arr) {
return arr.filter((item,
index) => arr.indexOf(item) === index);
}
I didn't understant the part written in spanish so I hope this is what you are looking for
This is a solution specific to your question. this is not a generic solution.
const data = [
{
atributos: {
Tallas: [
{ id: 0, name: "XS" },
{ id: 1, name: "S" },
],
},
},
{
atributos: {
Calzado: [
{ id: 0, name: "10" },
{ id: 1, name: "9.5" },
],
},
},
{
atributos: {
Tallas: [
{ id: 0, name: "XS" },
{ id: 1, name: "S" },
],
},
},
];
function uniqueArray(array) {
const resultObject = array.reduce((acc, eachValue) => {
let keys = Object.keys(eachValue.atributos);
keys.forEach((eachKey) => {
if (!acc[eachKey]) {
acc[eachKey] = [];
}
let list = eachValue["atributos"][eachKey].map(
(each) => each.id + "-" + each.name
);
acc[eachKey].push(...list);
});
return acc;
}, {});
const resultArray = Object.keys(resultObject).reduce((acc, each) => {
let setData = Array.from(new Set(resultObject[each]));
acc.push({
atributos: {
[each]: setData.map((e) => {
return { id: e.split("-")[0], name: e.split("-")[1] };
}),
},
});
return acc;
}, []);
return resultArray;
}
const result = uniqueArray(data)
console.log("result ", JSON.stringify(result, null, 2));

assign incremental index to nested array of object?

How to assign incremental index to nested array of object below? each members will have a property 1,2,3,4
groupMembersByTitle = [{
members: [{
id: 'uuid'
}, {
id: 'uuid'
}]
}, {
members: [{
id: 'uuid'
}, {
id: 'uuid'
}]
}]
I'm stuck here
const r = groupMembersByTitle.map(o => ({
...o,
members: o.members.map((o2, index) => ({
...o2,
no: ++index
}))
}))
You'll need a more persistent outer variable.
const groupMembersByTitle = [{
members: [{
id: 'uuid'
}, {
id: 'uuid'
}]
}, {
members: [{
id: 'uuid'
}, {
id: 'uuid'
}]
}];
let no = 1;
const mapped = groupMembersByTitle.map(
obj => ({
members: obj.members.map(
member => ({ ...member, no: no++ })
)
})
);
console.log(mapped);
You can use the map parameter thisArg.
map(function(element, index, array) { /* … */ }, thisArg)
const groupMembersByTitle = [{
members: [{ id: 'uuid' }, { id: 'uuid' }]
}, {
members: [{ id: 'uuid' }, { id: 'uuid' }]
}];
const r = groupMembersByTitle.map(function(o1) {
return ({
members: o1.members.map(
o2 => ({
...o2,
no: ++this.acc
})
)
});
}, { acc: 0 });
console.log(r);
function recursiveFunction(data, index) {
if(Array.isArray(data)) {
return data.reduce((acc, el) => this.recursiveFunction(el, acc), index);
} else if(data.members) {
return this.recursiveFunction(data.members, index);
} else {
data.no = index;
return index + 1;
}
}
const groupMembersByTitle = [
{
members: [
{
id: 'uuid'
},
{
id: 'uuid'
}
]
},
{
members: [
{
id: 'uuid'
},
{
id: 'uuid'
}
]
}];
const res = recursiveFunction(groupMembersByTitle, 0);
console.log(groupMembersByTitle);
console.log(res);
You can do it using Array.prototype.map twice and use the indices of the arrays to calculate the no.
const
data = [
{ members: [{ id: "uuid" }, { id: "uuid" }] },
{ members: [{ id: "uuid" }, { id: "uuid" }] },
],
result = data.map(({ members }, i) =>
members.map((m, j) => ({
...m,
no: i * (i ? data[i - 1].members.length : 1) + j + 1,
}))
);
console.log(result);

Intersection of two arrays in javascript

I want to search in a big array for different id from another array and print all intersections of those two arrays
I want to map through my bigTable and I want to create another array of correspondence, each found element must contain all fields+tableName+tableID like this :
const output = [{
ID: 1234,
title: 'title1',
TableName: 'loramIpsum',
TableId: 11,
},
{
ID: 98523,
title: 'mylasttitle',
TableName: 'table2',
TableId: 87545,
},
{
ID: 97766,
title: 'mylastdata',
TableName: 'table2',
TableId: 87545,
},
]
I've create a function but I think there is another best and sample solution, this is my function :
const getResult = (wantedData, bigArray) => {
return wantedData.flatMap((id) =>
bigArray.flatMap((family) =>
family.Tables.flatMap((table) => {
let item = table.myDatas.find((el) => el.ID === id);
if (item) {
item.Table = table.TableName;
item.familyId = family.GridId;
return item;
}
}).filter((result) => result !== undefined)
)
);
};
console.log(getResult(wantedData, bigArray))
<script>
const wantedData = [1235, 98523, 97766];
const bigArray = [{
bigArrayId: 1111,
Tables: [{
TableId: 11,
TableName: 'loramIpsum',
myDatas: [{
ID: 1234,
title: 'title1',
},
{
ID: 1235,
title: 'title2',
},
],
}, ],
},
{
bigArrayId: 674665,
Tables: [{
TableId: 87545,
TableName: 'table2',
myDatas: [{
ID: 98523,
title: 'mylasttitle',
},
{
ID: 24134,
title: 'alex',
},
{
ID: 97766,
title: 'mylastdata',
},
],
}, ],
},
];
</script>
Any help please ? Can I do it with recursive function ?
I think you need to solve this problem in two steps:
First, create a flat array of tables
Then filter the array by conditions
const bigArray=[{bigArrayId:1111,Tables:[{TableId:11,TableName:"loramIpsum",myDatas:[{ID:1234,title:"title1"},{ID:1235,title:"title2"}]}]},{bigArrayId:674665,Tables:[{TableId:87545,TableName:"table2",myDatas:[{ID:98523,title:"mylasttitle"},{ID:24134,title:"alex"},{ID:97766,title:"mylastdata"}]}]}];
const wantedData = [1235, 98523, 97766];
const flatTables = bigArray.flatMap(({ Tables }) =>
Tables.flatMap(({ myDatas, TableId, TableName }) =>
myDatas.map((data) => ({ ...data, TableId, TableName })) ));
const result = flatTables.filter(({ ID }) => wantedData.includes(ID));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I think if you do it something like this you'll be able to map after you've found the right things rather than mapping everything and then filtering that result:
const bigArray = [{ bigArrayId: 1111, Tables: [{ TableId: 11, TableName: 'loramIpsum', myDatas: [{ ID: 1234, title: 'title1', }, { ID: 1235, title: 'title2', }, ], }, ], }, { bigArrayId: 674665, Tables: [{ TableId: 87545, TableName: 'table2', myDatas: [{ ID: 98523, title: 'mylasttitle', }, { ID: 24134, title: 'alex', }, { ID: 97766, title: 'mylastdata', }, ], }, ], }, ];
const wantedData = [1235, 98523, 97766];
const wanted_set = new Set(wantedData);
const push_concat = (arr1, arr2) => {
for(let i = 0; i < arr2.length; i++)
arr1.push(arr2[i]);
return arr1;
};
const res = bigArray.reduce(
(acc, { Tables }) =>
push_concat(acc,
Tables.flatMap(({ TableId, TableName, myDatas }) =>
myDatas
.filter(({ ID }) => wanted_set.has(ID))
.map(({ ID, title }) => ({ ID, title, TableId, TableName }))
)
),
[]
);
console.log(res);

find sum of amount for group of list

I am new to Reactjs.
I have below data
Name Amount
Poorna 11000.00
Kumar 2900.00
Ashok 20000.00
Kumar 3020.00
Poorna 15000.00
Output should display like below
Name Amount
Poorna 26000.00
Kumar 5920.00
Ashok 20000.00
Please help me.
Use Array.reduce()
var sample= [
{ Name: 'Poorna', Amount: 50},
{ Name: 'Kumar', Amount: 50},
{ Name: 'Ashok ', Amount: 75},
{ Name: 'Poorna', Amount: 35},
];
var res = sample.reduce((a, obj)=>{
var existItem = a.find(item => item.Name=== obj.Name);
if(existItem){
existItem.Amount += obj.Amount;
return a;
}
a.push(obj);
return a;
}, []);
console.log(res);
Using reduce()
const array = [
{ id: 1, name: 'Poorna', amount: 11000 },
{ id: 2, name: 'Kumar', amount: 2900},
{ id: 3, name: 'Ashok', amount: 20000},
{ id: 3, name: 'Kumar', amount: 3020},
{ id: 3, name: 'Poorna', amount: 15000}
];
let output = Object.values(array.reduce((acc, curr) => {
if (acc[curr.name]) acc[curr.name].amount += curr.amount;
else acc[curr.name] = { ...curr };
return acc;
}, {}));
console.log(output);
You could do it using a Map:
import React from "react";
export default function App() {
const list = [
{ name: 'Poorna', amount: 11000 },
{ name: 'Kumar', amount: 2900 },
{ name: 'Ashok', amount: 20000 },
{ name: 'Kumar', amount: 3020 },
{ name: 'Poorna', amount: 15000 }
];
const map = new Map();
list.forEach(({ name, amount }) =>
map.set(name, map.has(name) ? map.get(name) + amount : amount));
const listItems = [...map.entries()].map(([name, amount]) => <li>{name}: {amount}</li>);
return <ul>{listItems}</ul>;
}
I think below is the best way.
const data = [
{ Name: 'Poorna', Amount: 11000 },
{ Name: 'Kumar', Amount: 2900 },
{ Name: 'Ashok', Amount: 20000 },
{ Name: 'Kumar', Amount: 3020 },
{ Name: 'Poorna', Amount: 15000 },
];
const result = data.reduce((prev, { Name, Amount }) => {
if (prev[Name]) return {...prev, [Name]: prev[Name] + Amount};
return {...prev, [Name]: Amount};
}, {});
This is how you can group the data according to names:
let data = [
{name: "Poorna", salary:11000.0},
{name: "Kumar",salary: 2900.0},
{name: "Ashok", salary:20000.0},
{name: "Kumar", salary:3020.0},
{name: "Poorna", salary:15000.0},
];
let sol = {};
for (let a of data) {
if (sol[a.name]) {
sol[a.name] += a.salary;
} else {
sol[a.name] = a.salary;
}
}
console.log(sol);
Here is full react app:
import React, { useState, useEffect } from "react";
import "./style.css";
let data = [
{ name: "Poorna", salary: 11000.0 },
{ name: "Kumar", salary: 2900.0 },
{ name: "Ashok", salary: 20000.0 },
{ name: "Kumar", salary: 3020.0 },
{ name: "Poorna", salary: 15000.0 }
];
export default function App() {
const [initialData, setInitialData] = useState(data);
const [group, setGroup] = useState([]);
const groupData = () => {
let sol = {};
for (let a of initialData) {
if (sol[a.name]) {
sol[a.name] += a.salary;
} else {
sol[a.name] = a.salary;
}
}
setGroup(sol);
};
useEffect(() => {
groupData();
}, []);
return (
<div>
<table>
<tr>
{" "}
<th>Name</th>
<th>Amount</th>
</tr>
{initialData.map(d => (
<tr>
{" "}
<td>{d.name}</td>
<td>{d.salary}</td>
</tr>
))}
</table>
<h2>Grouped data</h2>
<table>
<tr>
<th>Name</th>
<th>Amount</th>
</tr>
{group &&
Object.keys(group).map(key => (
<tr>
<td>{key}</td>
<td>{group[key]}</td>
</tr>
))}
</table>
</div>
);
}
You can find the Working app here : Stackblitz Link

Filter array inside array

I have the array as below
test_list = [
{
id: 1,
test_name: 'Test 1',
members: [
{
user_id: 3
},
{
user_id: 4
}
],
},
{
id: 2,
test_name: 'Test 2',
members: [
{
user_id: 4
},
{
user_id: 5
},
],
},
{
id: 3,
test_name: 'Test 2',
members: [
{
user_id: 8
},
{
user_id: 10
},
],
}
]
I want to filter the test for specific user_id, example if user_id = 4 I would like to have this result
{
id: 1,
...
},
{
id: 2,
...
},
I have tried with this but it only return the member
test_list.filter(function(item) {
item.members.filter(function(member) {
if(member.user_id === 4) {
return item;
}
});
})
Would anyone please help me in this case?
Check if .some of the objects in the members array have the user_id you're looking for:
test_list = [{
id: 1,
test_name: 'Test 1',
members: [{
user_id: 3
},
{
user_id: 4
}
],
},
{
id: 2,
test_name: 'Test 2',
members: [{
user_id: 4
},
{
user_id: 5
},
],
},
{
id: 3,
test_name: 'Test 2',
members: [{
user_id: 8
}]
}
];
const filtered = test_list.filter(
({ members }) => members.some(
({ user_id }) => user_id === 4
)
);
console.log(filtered);
You could use .reduce() and .filter() method of array to achieve required result.
Please check below working code snippet:
const arr = [{"id":1,"test_name":"Test 1","members":[{"user_id":3},{"user_id":4}]},{"id":2,"test_name":"Test 2","members":[{"user_id":4},{"user_id":5}]},{"id":3,"test_name":"Test 2","members":[{"user_id":8}]}];
const data = arr.reduce((r,{ members,...rest }) => {
let rec = members.filter(o => o.user_id === 4)
if(rec.length){
rest.members = rec;
r.push(rest);
}
return r;
},[]);
console.log(data);
Hope this works.
var members = item.members;
var filterById =members.filter((item1)=>{
return (item1.user_id===4)
});
return filterById.length > 0;
});
console.log(test_List_by_id)```

Categories

Resources