Better way to SUM previous to next value javascript - javascript

I have a below array:
[
{
"model": "A",
"count": "10",
"date": "02-12-2004"
},
{
"model": "B",
"count": "20",
"date": "02-01-2004"
},
{
"model": "C",
"count": "30",
"date": "02-02-2004"
}
]
I need a new array set to be like the following
[
{
"model": "A",
"count": "10",
"date": "02-12-2004"
},
{
"model": "B",
"count": "30",
"date": "02-01-2004"
},
{
"model": "C",
"count": "60",
"date": "02-02-2004"
}
]
It means that all previous set count should be added to the next set.

Try this.
arr=[{"model":"A", "count":"10","date":"02-12-2004"},{"model":"B", "count":"20","date":"02-01-2004"},{"model":"C", "count":"30","date":"02-02-2004"}]
count=0;
let arr2 = arr.filter(obj=>{
count+=parseInt(obj.count);
obj.count=count;
})
console.log(arr)
If you dont want to modify the existing array .Use Object.assign method like below
arr=[{"model":"A", "count":"10","date":"02-12-2004"},{"model":"B", "count":"20","date":"02-01-2004"},{"model":"C", "count":"30","date":"02-02-2004"}]
count=0;
let arr2 = arr.map(obj=>{
count += parseInt(obj.count);
return Object.assign({}, obj, {
count:count
});
});
console.log(arr2)

Related

Is there a way to compare dates and store them in an array?

I'm currently working on a website where Objects are sorted. The Objects are from a database where it's stored with a date (2022-10-13 02:07:11). Is there a way to compare dates and store the ones that are created on the same date? For example: If there are two objects that were created on 2022-10-13, but with at a different time, I would like to save these in an array with the name of the date.
I can't change how it's saved because it's not my DB.
I hope you understand how I mean it.
(I don't know how you want it or how your database is exactly so you might have to change some things)
Try using (something like) this:
let sorted = {};
// replace "data" below with your key
for(key in data){
if(!sorted[data[key].date]){
sorted[data[key].date] = [];
}
sorted[data[key].date].push({key: data[key]});
}
Example in my case:
let data = {
"a": {
"date": "2022-10-13 02:07:11"
},
"b": {
"date": "2022-10-13 00:00:00"
},
"c": {
"date": "2022-10-10 02:07:11"
}
};
let sorted = {};
for (key in data) {
if (!sorted[data[key].date]) {
sorted[data[key].date] = [];
}
sorted[data[key].date].push({
key: data[key]
});
}
console.log(sorted);
A reduce is useful here
Give us more details of the object to give a more tailored answer
const obj = [
{ "id": "a1", "date": "2022-10-13 01:07:11" },
{ "id": "a2", "date": "2022-10-13 02:07:11" },
{ "id": "a3", "date": "2022-10-13 03:07:11" },
{ "id": "b", "date": "2022-10-14 02:07:11" },
{ "id": "c1", "date": "2022-10-15 01:07:11" },
{ "id": "c2", "date": "2022-10-15 02:07:11" },
{ "id": "c3", "date": "2022-10-15 03:07:11" },
{ "id": "d", "date": "2022-10-16 01:07:11" }
];
const grouped = obj.reduce((acc,cur) => {
const key = cur.date.split(" ")[0];
(acc[key] = acc[key] || []).push(cur);
return acc;
},{})
console.log(grouped);

Javascript array equality control

Hi I have two changeable length arrays and I tried If there is no value I want, delete it from that array
array1 = [
{
"serial": "3",
"code": "1"
},
{
"serial": "700",
"code": "1"
},
{
"serial": "300",
"code": "1"
},
{
"serial": "400",
"code": "1"
}
]
array2 = [{
"someting": 10,
"someting2": "20",
"serialList": ["700","711"],
},
{
"someting": 10,
"someting2": "30",
"serialList": ["300"],
},
{
"someting": 0,
"someting2": "0",
"serialList": [],
}
]
this my two array as I said arrays length is changeable sometimes array1 length big, sometimes array2 and I want If serial number in array1 does not exist in array2 delete from array1 element,
according to above array1[0] and array1[3] serial codes does not exist any element of array2 I want to output array1 is:
array1 = [
{
"serial": "700",
"code": "1"
},
{
"serial": "300",
"code": "1"
}
]
How can I do that, thnx
here is a simple and readable approach to achieve that
let allowedSerials = array2.map( obj=> obj.serialList ).flat();
let result = array1.filter( obj => allowedSerials.includes(obj.serial) )
check the snippet below:
let array1 = [
{
"serial": "3",
"code": "1"
},
{
"serial": "700",
"code": "1"
},
{
"serial": "300",
"code": "1"
},
{
"serial": "400",
"code": "1"
}
]
let array2 = [{
"someting": 10,
"someting2": "20",
"serialList": ["700","711"],
},
{
"someting": 10,
"someting2": "30",
"serialList": ["300"],
},
{
"someting": 0,
"someting2": "0",
"serialList": [],
}
];
// straight-forward solution:
let allowedSerials = array2.map( obj=> obj.serialList ).flat();
let result = array1.filter( obj => allowedSerials.includes(obj.serial) )
console.log(result);

How to get the sum of children values of an object in a Javascript react native?

Here is my object:
var obj = {
"idtransact1": {
"amount": 3000,
},
"idtransact2": {
"amount": 3000,
}
}
I am trying to get the sum of all amount.
I tried to adapt this example but since it is not the same data structure then i am a bit lost.
var array = [{
"adults": 2,
"children": 3
}, {
"adults": 2,
"children": 1
}];
var val = array.reduce(function(previousValue, currentValue) {
return {
adults: previousValue.adults + currentValue.adults,
children: previousValue.children + currentValue.children
}
});
console.log(val);
Any help would be appreciated.
You can use Object.values() and .reduce() to get the sum:
const data = {
"idtransact1": { "amount": 3000 },
"idtransact2": { "amount": 3000 }
};
const result = Object.values(data).reduce((r, { amount }) => r + amount, 0);
console.log(result);
Using forEach loop
var obj = {
"idtransact1": {
"amount": 3000,
},
"idtransact2": {
"amount": 3000,
}
}
var sum=0;
Object.values(obj).forEach((x)=>sum+=x.amount)
console.log(sum)
A for in loop is your friend when it comes to looking for values in an object.
var obj = {
"idtransact1": {"amount": 3000},
"idtransact2": {"amount": 3000}};
var sumAmount = 0;
for(var char in obj){
sumAmount += obj[char].amount;
}
console.log(sumAmount);
For your second example, the for in loop works the same way with the array of objects.
var array = [
{"adults": 2,"children": 3},
{"adults": 2,"children": 1}];
var sumAdults = 0;
var sumChildren = 0;
for(var char in array){
sumAdults += array[char].adults;
sumChildren += array[char].children;
}
console.log(sumAdults + " " + sumChildren);
Less to remember if you can look for data in objects and data in an array of objects the same way. Enjoy
Array [
Object {
"product": Object {
"cat_id": "20",
"cat_name": "Pizza",
"detail": "Pizza sauce, Green pepper & mozarella cheese",
"discount_price": "",
"has_extra": "0",
"has_variation": "1",
"id": "46",
"image": "chicken-tikka-piza-recipe-main-photo.jpg",
"name": "Chicken Fajita",
"prep_time": "30",
"price": "310",
"status": "1",
"time_stamp": "2021-01-02 19:43:41",
"ven_id": "6",
},
"quantity": 1,
},
Object {
"product": Object {
"cat_id": "20",
"cat_name": "Pizza",
"detail": "Pizza Sauce, Tomato Green Paper, Olives Mashrooms And Chipotle Sauce with extra Creamy mayoneese",
"discount_price": "",
"has_extra": "0",
"has_variation": "0",
"id": "45",
"image": "chicken-tikka-piza-recipe-main-photo.jpg",
"name": "Chicken Tikka",
"prep_time": "15",
"price": "310",
"status": "1",
"time_stamp": "2021-01-02 19:41:56",
"ven_id": "6",
},
"quantity": 3,
},
]
How to calculate its total price where quantity is not the same also I want to calculate total price

How to merge/combine array of objects based on duplicate keys?

I am trying to merge data on any duplicate key but also rewrite the data object.
I am trying to merge the array of values depending on if each object has the same 'time'. After which, I would like to pair each value within the items with the name.
I think the easiest way to show is through the raw data I hope to transform, So I would like to transform the following;
var data = [{
"item": ["1", "2"],
"time": "12-15",
"name": "ben"
}, {
"item": ["3", "4"],
"time": "12-15",
"name": "bill"
}, {
"item": ["1", "2", "3"],
"time": "15-18",
"name": "ben"
}, {
"item": ["4", "5", "6"],
"time": "15-18",
"name": "bill"
}];
Into
var result = [{
"time": "12-15",
"ben": ["1", "2"],
"bill": ["3", "4"]
},
{
"time": "15-18",
"ben": ["1", "2", "3"],
"bill": ["4", "5", "6"]
}]
I have been trying to this this question to help me do this however I'm not getting very far. I cannot seem to resolve the issue of the first item that is checked not being output as an array.
Any help is much appreciated!
var data = [{
"item": ["1", "2"],
"time": "12-15",
"name": "ben"
}, {
"item": ["3", "4"],
"time": "12-15",
"name": "bill"
}, {
"item": ["1", "2", "3"],
"time": "15-18",
"name": "ben"
}, {
"item": ["4", "5", "6"],
"time": "15-18",
"name": "bill"
}];
var seen = {};
var result = data.filter(function(entry) {
var previous;
// Have we seen this label before?
if (seen.hasOwnProperty(entry.time)) {
// Yes, grab it and add this data to it
previous = seen[entry.time];
previous.item.push(entry.item);
// Don't keep this entry, we've merged it into the previous one
return false;
}
//console.log(seen)
// entry.data probably isn't an array; make it one for consistency
if (!Array.isArray(entry.item)) {
entry.item = [entry.item];
}
// Remember that we've seen it
seen[entry.time] = entry;
// Keep this one, we'll merge any others that match into it
return true;
});
console.log(result)
You could use a hash table for grouping.
var data = [{ "item": ["1", "2"], "time": "12-15", "name": "ben" }, { "item": ["3", "4"], "time": "12-15", "name": "bill" }, { "item": ["1", "2", "3"], "time": "15-18", "name": "ben" }, { "item": ["4", "5", "6"], "time": "15-18", "name": "bill" }],
result = [];
data.forEach(function (a) {
if (!this[a.time]) {
this[a.time] = { time: a.time };
result.push(this[a.time]);
}
this[a.time][a.name] = (this[a.time][a.name] || []).concat(a.item);
}, Object.create(null));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Or with ES6 you could use a Map.
var data = [{ "item": ["1", "2"], "time": "12-15", "name": "ben" }, { "item": ["3", "4"], "time": "12-15", "name": "bill" }, { "item": ["1", "2", "3"], "time": "15-18", "name": "ben" }, { "item": ["4", "5", "6"], "time": "15-18", "name": "bill" }],
map = new Map,
result = [];
data.forEach(a => {
var o = map.get(a.time);
if (!o) {
o = { time: a.time };
map.set(a.time, o);
result.push(o);
}
o[a.name] = (o[a.name] || []).concat(a.item);
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I would like to follow this approach creating two functions and returning a new object with the merged data, this way you avoid the mutation of your original object.
Note: this uses ES6 syntax but you can easily transform this code into ES5.
const data = [{
"item": ["1", "2"],
"time": "12-15",
"name": "ben"
}, {
"item": ["3", "4"],
"time": "12-15",
"name": "bill"
}, {
"item": ["1", "2", "3"],
"time": "15-18",
"name": "ben"
}, {
"item": ["4", "5", "6"],
"time": "15-18",
"name": "bill"
}];
// Get a list of unique times
const getTimes = data => data.reduce((a, c) => {
if (!a.includes(c.time)) {
a.push(c.time);
}
return a;
}, []);
// Merge the data into a single list using the times list as index
const mergeData = (data, times) => times.map(time => {
const obj = {};
obj.time = time;
data.forEach(record => {
if (record.time === time) {
obj[record.name] = record.item;
}
});
return obj;
});
const times = getTimes(data);
const result = mergeData(data, times);
console.log(result);
You can do it just with map() and filter() plus an inner loop like this :
var data = [{
"item": ["1", "2"],
"time": "12-15",
"name": "ben"
}, {
"item": ["3", "4"],
"time": "12-15",
"name": "bill"
}, {
"item": ["1", "2", "3"],
"time": "15-18",
"name": "ben"
}, {
"item": ["4", "5", "6"],
"time": "15-18",
"name": "bill"
}];
var skel = data.map(x => x.time).filter((x,i,arr) => arr.indexOf(x) === i).map(x => ({"time" : x}));
var result = skel.map(x => {
data.forEach(y => {
if(x.time === y.time)
x[y.name] = y.item;
})
return x;
} )
console.log(result);
You may do as follows;
var data = [{
"item": ["1", "2"],
"time": "12-15",
"name": "ben"
}, {
"item": ["3", "4"],
"time": "12-15",
"name": "bill"
}, {
"item": ["1", "2", "3"],
"time": "15-18",
"name": "ben"
}, {
"item": ["4", "5", "6"],
"time": "15-18",
"name": "bill"
}],
interim = data.reduce((h,d) => (h[d.time] = h[d.time] ? h[d.time].concat({[d.name]: d.item})
: [{[d.name]: d.item}],h),{}),
result = Object.keys(interim)
.map(k => Object.assign({time: k},...interim[k]));
console.log(result);
It might be helpful to write a function to group stuff by time:
class DefaultMap extends Map {
constructor(defaultConstructor) {
super();
this.defaultConstructor = defaultConstructor;
}
get(key) {
if (this.has(key)) {
return super.get(key);
}
const def = this.defaultConstructor();
this.set(key, def);
return def;
}
}
function groupBy(collection, key) {
const groups = new DefaultMap(() => []);
for (const item of collection) {
const itemKey = key(item);
const group = groups.get(itemKey);
group.push(item);
}
return groups;
}
Then you can just:
const result =
groupBy(data, entry => entry.time).entries().map(
([time, entries]) => {
const group = {time};
entries.forEach(entry => {
group[entry.name] = entry.item;
});
return group;
}
);
Try this
var timeGroup = _.groupBy(data,"time");
_.mapObject(timeGroup,function(val,key){
var benArray = _.flatten(_.values(_.pick(_.findWhere(val, {name:"ben"}),"item")));
var billArray = _.flatten(_.values(_.pick(_.findWhere(val,{name:"bill"}),"item")));
console.log({"time" : key,"ben" : benArray , "bill" : billArray })
})

split out object property and values from an array [duplicate]

This question already has answers here:
Remove a JSON attribute [duplicate]
(2 answers)
Closed 7 years ago.
From this json arrays
{
"result": [
{
"id": "1",
"name": "John",
"type": "B",
"score":"passed"
},
{
"id": "2",
"name": "Alice",
"type": "A",
"score":"failed"
}
]
}
How to split out some field and turn it intosomething like this
{
"result": [
{
"id": "1",
"type": "B",
},
{
"id": "2",
"type": "A",
}
]
}
I do not want to use splice in my case, above is just sample code.
Try this:
var input = {
"result": [
{
"id": "1",
"name": "John",
"type": "B",
"score":"passed"
},
{
"id": "2",
"name": "Alice",
"type": "A",
"score":"failed"
}
]
};
var output = {
result: input.result.map(function(item) {
return {
id: item.id,
type: item.type
};
})
}
Try like this
var json = {
"result": [{
"id": "1",
"name": "John",
"type": "B",
"score": "passed"
}, {
"id": "2",
"name": "Alice",
"type": "A",
"score": "failed"
}
]
};
json.result.forEach(function(item) {
delete item.name;
delete item.score;
});
console.log(json);
iterate over arry and remove age property
var json = [
{"name":"john",
"age":"30",
"gender":"male"},
{"name":"Alice",
"age":"20",
"gender":"female"}
];
json.forEach(function(x){
delete x['age'];
})

Categories

Resources