How to get sum of json array - javascript

So, I am fetching values from a database and then i am returning/using them in JSON/javascript as an array for example as shown here
The problem is that I want the sum of the array elements.
I used this code:
var obj1 = JSON.parse(data);
var mar = obj1.march;
var quantite = obj1.quant;
const sum = quantite.reduce((result,number)=> result+number);
console.log(sum);
And here is what I got in the console
I am totally new into JSON and javascript, so, any tips/help would be great for me!

The elements in the array are strings and so, when you use the + operator it concatenates them. You want to parse them first like this:
const sum = quantite.reduce((result,number)=> parseInt(result) + parseInt(number));

Seems that you data contains strings, not int.
You can improve your reduce function:
quantite.reduce((result,number) => parseInt(result)+parseInt(number));

Use the start value of reduce() and make sure number isn't a string when adding it
quantite.reduce((res,num)=> (res + Number(number)),0);
// start value ^^^

Related

Get Data from Array Without Quotes

I having a problem with an array inside a JavaScript, and I don't how I can get the data from inside the array. This is the code:
array = [A(-11.8,166.88),A(-11.8,166.88),A(-11.8,166.88)]
function A(a,b) {
polyCoords.push(projTransform(a,b));
}
I want to get each lat and long separate in javascript format, but I don't know how I can proceed. Probably is more easier than I think, but currently I block with this.
Do you have any idea on how can I proceed?
The result that I want is to obtain this data.
array[0] = [-11.8,166.88]
array[1] = [-11.8,166.88]
array[2] = [-11.8,166.88]
Thanks in advance
var array = [A(-11.8,166.88),A(-11.8,166.88),A(-11.8,166.88)];
function A(a,b) {
//polyCoords.push(projTransform(a,b));
//you need to return a value, otherwise the result of the method
//is undefined
return [a, b];
}
console.log(array);
console.log(array[0][0], array[0][1]);
console.log(array[1][0], array[1][1]);
console.log(array[2][0], array[2][1]);
To me it looks like you want to define the array and then add it to polyCoords.
var array = [[-11.8,166.88],[-11.8,166.88],[-11.8,166.88]];
array.forEach(el => polyCoords.push(projTransform(el[0], el[1])));

Get data from this json string

I have a json string
["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]
I need to get at the data only and I want to extract the string to get the following :
https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg
I have tried to use JSON.parse but this does not seem to work
Any help woul dbe appreciated
[] represents an array on JSON. {} represents an Object.
So in order to fetch the first element from you json string, you have to parse the string as a JSON element ;
var arr = JSON.parse('["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]');
OR when you HAVE a json array already;
var arr = ["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"];
Then, go on and fetch the first value from your array which has index 0 as in all programming languages.
var url = arr[0];
It's seems to be a normal array not a JSON, but if you want you can treat it as JSON:
var image = JSON.parse('["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]')[0];
console.log(image); //https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg
Be aware of the difference between an array, and a JSON object.
I have given some examples of the differences and how to access them.
// This is an array containing 1 value.
myobj = ["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"];
// it can be accessed by either the array name (since it only hase one value) or the array name and index of the value in cases where the array actually has more than one value.
var example1 = [myobj];
document.write("This is my single value array:<br>" + example1 + "<br><br>");
// This is probably best practice regardless of the number of items in the array.
var example2 = myobj[0];
document.write("Now im specificing the index, incase there are more that one urls in the array:<br>" + example1 + "<br><br>");
// This is a JSON object
myJsonObj = {"url":"https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"}
// You access the value of the URL like this:
var example3 = myJsonObj.url;
document.write("Here is the value from a JSON object:<br>" + example3 );
Hope this helps
Just use parse function:
var text = '["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]';
var obj = JSON.parse(text);
https://jsfiddle.net/esouc488/1/

Adding Characters to the Begining of an Array that form words

When looking at set of characters I am trying to put each letter into a specifc order in an array. For Example: Given the Strings "cat" and "dog" I would want an array that contains [d,o,g,c,a,t], cat at the end of the array because it was read first.
Currently I have tried this:
However, when I try the code below assuming the strings are "cat" and "dog".
I get an array containing: [c,a,t,d,o,g]. Instead of push I have also tried .unshift but the array now reads: [g,o,d,t,a,c].
var chars = /^[a-z]$/;
var string = [];
function makeword(){
if(currentChar.match(chars)){
string.push(currentChar);
currentChar = getNextChar(); //Gets next Character in the String
makeword();
}
}
Is something like this possible in Javascript?
If I understood you correctly, you want to provide a list of strings, then have them show up in an array in reverse order, with each letter as an element of the array. The following function will do just that:
function makeWords() {
var arr = [];
for(var i = arguments.length - 1; i >=0; i--) {
arr.push(arguments[i]);
}
return arr.join('').split('');
}
so running makeWords('cat', 'dog') will result in ['d','o','g','c','a','t'].
It's a relatively simple code when a functional approach is used. The rest and spread operators are very handy both to collect the function arguments and to spread the characters of a word into an array.
var characterify = (...c) => c.reduceRight((a,b) => a.concat([...b]) ,[]);
document.write("<pre>" + JSON.stringify(characterify("cat","dog")) + "</pre>");

Access value from JavaScript object via array-string

my problem is that i have a json-object with and array into here an example.
var object = {
'items':['entry1','entry2']
}
I want to access 'entry2' over a constant string that I receive and shouldn't be changed.
var string = 'items[1]';
The only way I'm solving this problem is over the eval function...
eval('object.'+string);
This returns me entry2.
Is there any other way to achieve this without using eval()?
Like object[string] or object.string
Supposing your string is always the same form, you could extract its parts using a regex :
var m = string.match(/(\w+)\[(\d+)\]/);
var item = object[m[1]][+m[2]];
Explanation :
The regex builds two groups :
(\w+) : a string
\[(\d+)\] : some digits between brackets
and those groups are at index 1 and 2 of the array returned by match.
+something parses the number. It's not strictly needed here as the array accepts a string if it can be converted but I find the code more readable when this conversion is explicited.
On top of dystroy's anwser, you can use this function:
function getValueFromObject(object, key) {
var m = key.match(/(\w+)\[(\d+)\]/);
return object[m[1]][+m[2]];
}
Example:
var object = {
'items':['entry1','entry2']
}
var string = 'items[1]';
var value = getValueFromObject(object, string); //=> "entry2"
First, you can get the array from inside:
var entries = object.items // entries now is ['entry1','entry2']
Then you need to index that to get the second item (in position 1). So you achieve what you want with:
var answer = entries[1] // answer is now 'entry2'
Of course, you can combine this to get both done in one step:
var answer = object.items[1] // answer is now 'entry2'
... I can see this is a contrived example, but please don't call your Objects 'object', or your Strings 'string' :s
try something like this
object.items[1];

JavaScript split string to array of int

I have a string that's on the page and from which I want an array of int.
<div id="TheData">2,3,0,43,23,53</div>
I'm writing this:
var ArrayData = ($('#TheData').html()).split(',');
However, ArrayData becomes an array of strings. How can I get an array of ints? Note that some of the elements in the HTML can be equal to 0.
Thanks.
var ArrayData = $('#TheData').html().split(',').map( Number );
Add Array.prototype.map() to older browsers with the code from MDN.
You can use jQuery's $.map() in the same manner, though it won't work with $.prototype.map().
var ArrayData = $.map( $('#TheData').html().split(','), Number );
var ArrayData = $.map($('#TheData').text().split(','), function(value){
return parseInt(value, 10);
// or return +value; which handles float values as well
});
You can use $.map to transform the array of strings to ints by calling parseInt on each of the elements in the array
Pure Javascript solution:
const elementText = document.getElementById('divSourceID').innerText;
const numericList = elementText.split(',').map(Number);
For more information:
getElementById: "The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly. (...)". Source: developer.mozilla.org.
Array.prototype.map: "The map() method creates a new array populated with the results of calling a provided function on every element in the calling array". Source: developer.mozilla.org.
array.map(Number): This call means the first received argument will be automatically converted into number and results in the same as if you explicitly declare the arrow function:
const numericList = elementText.split(',').map(Number);
same result as:
const numericList = elementText.split(',').map(str => Number(str));
JIT: Special thanks to #Robbendebiene for the excellent code review, simplifying the previous code.
var ArrayData = $('#TheData').text().split(',').map(Number);
You can find more here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Here is a simple answer
let x = "1,2,3,4";
let result = x.split(",").map((e) => parseInt(e));
console.log(result);
var ArrayData = $('#TheData').html().split(',').map( d => { return parseInt(d) });
Use map function after Split, in callback of map you can parse that Integer

Categories