Related
I am developing a javascript-based application, therein I have an array as below:
[-12.66, 268.2, 48.99, -1264.5, 20550, 91.2, 0, 0, 0, 0, 0, 0, 0, 0, 9235.5, 1500, 0, 0, 18.99, 0, 0, null, null, null, null, null, null, null, null, null, null]
now I want to do cumulative summation of below error until it returns null value, once it has started reading null value it should return null from there or should return as it is and should not do cumulative summation from there.
I have done as below using array.reduce:
let resultArray=[];
array1.reduce(function (acc, curr, index) { return resuleArray[index] = acc + curr }, 0);
// here array1 is source array.
However, this returns as below
[-12.66, 255.54, 304.53, -959.97, 19590.03, 19681.23, 19681.23, 19681.23, 19681.23, 19681.23, 19681.23, 19681.23, 19681.23, 19681.23, 28916.73, 30416.73, 30416.73, 30416.73, 30435.72, 30435.72, 30435.72, 30435.72, 30435.72, 30435.72, 30435.72, 30435.72, 30435.72, 30435.72, 30435.72, 30435.72, 30435.72];
What I would like to have is like below :
[-12.66, 255.54, 304.53, -959.97, 19590.03, 19681.23, 19681.23, 19681.23, 19681.23, 19681.23, 19681.23, 19681.23, 19681.23, 19681.23, 28916.73, 30416.73, 30416.73, 30416.73, 30435.72, 30435.72, null, null, null, null, null, null, null, null, null, null, null];
Please note that I will always have trailing values as null.
So, check if curr is null.
const array1 = [-12.66, 268.2, 48.99, -1264.5, 20550, 91.2, 0, 0, 0, 0, 0, 0, 0, 0, 9235.5, 1500, 0, 0, 18.99, 0, 0, null, null, null, null, null, null, null, null, null, null];
let resultArray = [];
array1.reduce(function(acc, curr, index) {
const sum = acc + curr;
if (curr === null) {
resultArray[index] = null;
} else {
resultArray[index] = sum
}
return sum;
}, 0);
console.log(resultArray);
This way even if you put a number after some null values it will continue with the cumulative summation
You need just to modify a little bit your code like this:
array1.reduce(function (acc, curr, index) {
return resultArray[index] = curr !== null ? acc + curr : null
}, 0);
Insert null in rest of the index once null is interpreted
const array1 = [-12.66, 268.2, 48.99, -1264.5, 20550, 91.2, 0, 0, 0, 0, 0, 0, 0, 0, 9235.5, 1500, 0, 0, 18.99, 0, 0, null, null, null, null, null, null, null, null, null, null];
let resultArray = [];
let isNullInterpreted = false;
const output = array1.reduce(function (acc, curr, index) {
isNullInterpreted = isNullInterpreted || curr == null;
return resultArray[index] = isNullInterpreted ? null : acc + curr;
}, 0);
console.log(resultArray);
console.log(output);
Stop iterating the loop once null is interpreted
const array1 = [-12.66, 268.2, 48.99, -1264.5, 20550, 91.2, 0, 0, 0, 0, 0, 0, 0, 0, 9235.5, 1500, 0, 0, 18.99, 0, 0, null, null, null, null, null, null, null, null, null, null];
let resultArray = [];
let isNullInterpreted = false;
const output = array1.reduce(function (acc, curr, index) {
isNullInterpreted = isNullInterpreted || curr == null;
if (!isNullInterpreted) {
resultArray[index] = acc + curr;
}
return resultArray[resultArray.length - 1]
}, 0);
console.log(resultArray);
console.log(output);
You could take a closure over the sum and add unil the value is null.
const
data = [-12.66, 268.2, 48.99, -1264.5, 20550, 91.2, 0, 0, 0, 0, 0, 0, 0, 0, 9235.5, 1500, 0, 0, 18.99, 0, 0, null, null, null, null, null, null, null, null, null, null],
result = data.map((sum => v => sum === null || v === null
? sum = null
: sum += v
)(0));
console.log(...result);
I have json data like
[ [ RowDataPacket { content_id: 52 } ],
OkPacket {
fieldCount: 0,
affectedRows: 0,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0 } ]
How I get content_id part from this data set?
I got this data while calling a Stored Procedure using TypeORM.
here is the code I tried
const contentData = await connection.getRepository(Content).query('CALL getInitialContent()');
To be a valid JS object literal, your data would have to look like this:
[
[ { RowDataPacket: { content_id: 52 } } ],
{ OkPacket: { fieldCount: 0, affectedRows: 0, insertId: 0, serverStatus: 2, warningCount: 0, message: '', protocol41: true, changedRows: 0}
}
];
Once you have that, then getting the content_id field is reasonably trivial as long as you can comprehend the data structure - it's inside the first element of an array, which itself is an array. The first element of that inner array is an object. That then contains another object inside the "RowDataPacket" object, and and the content_id data you want is a property of that second object.
Shorthand version:
let data = [
[{
RowDataPacket: {
content_id: 52
}
}],
{
OkPacket: {
fieldCount: 0,
affectedRows: 0,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}
}
];
let id = data[0][0].RowDataPacket.content_id;
console.log(id);
Longhand (so you can see the traversal of the data hierarchy step by step):
let data = [
[{
RowDataPacket: {
content_id: 52
}
}],
{
OkPacket: {
fieldCount: 0,
affectedRows: 0,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}
}
];
let arr = data[0]; //get inner array
let obj = arr[0]; //get object inside the array
let packetObj = obj.RowDataPacket; //get object in the RowDataPacket property
let id = packetObj.content_id; //get the target data
console.log(id);
I have an object list like this, I am getting this response from one of the api:
{
"1/22/20": {
"new_daily_deaths": 0,
"total_cases": 1,
},
"1/23/20": {
"new_deaths": 0,
"total_cases": 10,
},
"1/24/20": {
"new_deaths": 0,
"total_cases": 20
}
}
Expected Output:
{
x:1/22/20,1/23/20,1/24/20 // key of every object
y:1,10,20 //total_cases
}
Please help me how can we achieve this. I tried object.stringify but its not giving me an expected output.
You can use Object.keys() & Object.entries() methods for this like:
const data = {
"1/22/20": {
"new_daily_deaths": 0,
"total_cases": 1,
},
"1/23/20": {
"new_deaths": 0,
"total_cases": 10,
},
"1/24/20": {
"new_deaths": 0,
"total_cases": 20
}
}
const keys = Object.keys(data).join(',')
const cases = Object.entries(data).map(([k,v]) => v).map(x=>x.total_cases).join(',')
const result = { x: keys, y: cases}
console.log(result)
output as {x:1/22/20, y:1}, {x:1/23/20,y:10}
const data = {
"1/22/20": {
"new_daily_deaths": 0,
"total_cases": 1,
},
"1/23/20": {
"new_deaths": 0,
"total_cases": 10,
},
"1/24/20": {
"new_deaths": 0,
"total_cases": 20
}
}
const result = Object.entries(data).map(([k,v]) => ({x: k, y: v.total_cases}))
console.log(result)
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 5 years ago.
I'm trying to make an api for a bus ticketing sistem, but I can't seem to get an how to make it work in nodejs
[
{
"id":1,
"hour" : "7:30am"
, "seats" : [
0 ,
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0 ,0, 0
]
},
{
"id":2,
"hour" : "9:00am",
"seats" : [
0 ,
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0 ,0, 0
]
}
This is my mongodb query
db.schedules.update({"id":2}, {"$set" : {"seats.8" : "1"}});
and everything seems to work just fine until I try it on nodejs
router.put('/reserve/:id/:seat', function(req, res, next) {
schedules.update({"id": req.params.id}, { "$set":{ "seats." + req.params.seat+: "1"}}, function(err, doc) {
if (err) {
console.log(err);
return res.status(400).json({"error"});
}
if (doc.result.nModified) {
res.status(200).json({"status": "ok"});
} else {
res.status(400).json({"error": "The seat hasn't been reserved"});
}
});
this is the error returned:
SyntaxError: Unexpected token +
I have tried multiple ways and can't get that working
You have invalid javascript syntax here: schedules.update({"id": req.params.id}, { "$set":{ "seats." + req.params.seat+: "1"}} Can't concat a string in an object definition.
Try like this, using a property reference notation (that will create the property):
let updateObj = { $set: {} }
updateObject.$set['seats.' + req.params.seat] = '1'
schedules.update({"id": req.params.id}, updateObj, function ... )
This i have to admin has always been my Achilles tendon despite my years of experience in programming.
I have a json result looking like this from which I want to draw a time series using highcharts.com
[{"iso-2":"DE","year":"2000","value":"0"},{"iso-2":"FR","year":"2000","value":"0"},{"iso-2":"KE","year":"2000","value":"0"},{"iso-2":"DE","year":"2001","value":"0"},{"iso-2":"FR","year":"2001","value":"0"},{"iso-2":"KE","year":"2001","value":"0"},{"iso-2":"DE","year":"2002","value":"0"},{"iso-2":"FR","year":"2002","value":"0"},{"iso-2":"KE","year":"2002","value":"0"},{"iso-2":"DE","year":"2003","value":"9355"},{"iso-2":"FR","year":"2003","value":"19490"},{"iso-2":"KE","year":"2003","value":"0"},{"iso-2":"DE","year":"2004","value":"0"},{"iso-2":"FR","year":"2004","value":"0"},{"iso-2":"KE","year":"2004","value":"0"},{"iso-2":"DE","year":"2005","value":"11"},{"iso-2":"FR","year":"2005","value":"8"},{"iso-2":"KE","year":"2005","value":"0"},{"iso-2":"DE","year":"2006","value":"2"},{"iso-2":"FR","year":"2006","value":"1388"},{"iso-2":"KE","year":"2006","value":"0"},{"iso-2":"DE","year":"2007","value":"0"},{"iso-2":"FR","year":"2007","value":"0"},{"iso-2":"KE","year":"2007","value":"0"}]
I'd like to dynamically generate the above result into an arrays that looks like this
series: [{
name: 'KE',
data: [0,0,0,0,0,0,0,0]
}, {
name: 'FR',
data: [0,0,0,19490,0,8,1388,0]
}, {
name: 'DE',
data: [0,0,0,9355,0,2,0]
}]
Thank you so much for looking into this
var gathered = data.reduce(function(prev, curr) {
if (prev.hasOwnProperty(curr["iso-2"])) {
prev[curr["iso-2"]].push(parseInt(curr["value"]));
} else {
prev[curr["iso-2"]] = [parseInt(curr["value"])];
}
return prev;
}, {});
var result = [];
for (var country in gathered) {
var obj = {};
obj["name"] = country;
obj["data"] = gathered[country];
result.push(obj);
}
console.log(result);
Output
[ { name: 'DE', data: [ 0, 0, 0, 9355, 0, 11, 2, 0 ] },
{ name: 'FR', data: [ 0, 0, 0, 19490, 0, 8, 1388, 0 ] },
{ name: 'KE', data: [ 0, 0, 0, 0, 0, 0, 0, 0 ] } ]
Here's what I can think of, considering the data you have in the JSON is sorted by year:
var json_data = '[{"iso-2":"DE","year":"2000","value":"0"},...]'; // This is the json data you have.
var data = JSON.parse(json_data); // Convert JSON data to javascript object or array
// Organize the data in an object
var organized = {};
data.forEach(function (item){
if (typeof organized[item['iso-2']] !== 'undefined'){
organized[item['iso-2']].push(item['value']);
} else {
organized[item['iso-2']] = [item['value']];
}
});
// Convert the object to the format you need
var series = [];
for (i in organized){
series.push({
name: i,
data: organized[i]
});
}