calculate JSON.stringify(obj) to sum value of string? [duplicate] - javascript

This question already has answers here:
Fastest JavaScript summation
(11 answers)
Closed 10 months ago.
In my local storage I have some score value stored in array
var obj = localStorage.getItem("scoreList")
output
[0,10,10,0,10]
I want sum of this value like and return to data value
sum = 30
I have tried to convert into string value
var string = JSON.stringify(obj);
output "[0,10,10,0,10]"
How can I execute this sum value ?

[0,10,10,0,10].reduce((sum, a) => sum + a, 0);

localStorage.getItem("scoreList").replace(/(\[|\])/g, '').split(",").map(x => parseFloat(x)).reduce((a,b) => a+b, 0)
a simple way:
JSON.parse(localStorage.getItem("scoreList")).reduce((x, y) => x + y)

If you set the scoreList value as an array, that is:
localStorage.setItem('scoreList', [0,10,10,0,10])
When you get it back it will still be a string, so there's no need for any other kind of validation or data type transformation as you did with JSON.stringfy. The following shoud be enough:
const obj = localStorage.getItem("scoreList")
const total = obj.reduce((sum, item) => sum + item, 0);
//total = 30

Related

How to take array of numbers as input in Javascript? [duplicate]

This question already has answers here:
How to convert a string of numbers to an array of numbers?
(18 answers)
Closed 2 years ago.
"use strict";
let arr = readline().split(" "); // suppose inputs are 1 2 3 4 5
let res=0;
for(let i=0; i<arr.length; i++){
res += arr[i];
}
print(res); // output 012345
I know if I iterate through all the array elements and convert them to Number like arr[index] = Number(arr[index]); then I can get rid from this concatenation and will get pure sum.
But is there any way to convert all of these array elements of Strings to Number directly? without any iteration?
use Array.reduce:
let arr = readline().split(" "); // suppose inputs are 1 2 3 4 5
let res=arr.reduce((acc,e) => +e + acc,0);
"But is there any way to convert all of these array elements of Strings to Number directly?
Computationally, no. That's impossible. Iteration must happen. Otherwise it's like asking how you can visit every person on earth without having to travel.
But if you want to simplify your code by using functional programming then use Array.prototype.map:
const arrayOfInts = readLine().split( ' ' ).map( e => parseInt( e, 10 ) );
Take this further by performing sum with Array.prototype.reduce (also adding a filter to exclude NaN values which would break the summing operation):
I've documented the data-type of each chained function's return value on each line:
const sum = readLine() // string
.split( ' ' ) // string[]
.map( e => parseInt( e, 10 ) ) // ( number | NaN )[]
.filter( n => !isNaN( n ) ) // number[]
.reduce( ( acc, n ) => acc + n ); // number
You can not do it without iterating over it. However, you already loop through the array, so...
Just convert them in the loop where you add them:
"use strict";
let arr = readline().split(" "); // suppose inputs are 1 2 3 4 5
let res=0;
for(let i=0; i<arr.length; i++){
res += Number(arr[i]);
}
print(res); // output 15

Sort array in weird way [duplicate]

This question already has an answer here:
jQuery sort array value in sequence
(1 answer)
Closed 3 years ago.
Suppose I have an array like this:
let array = ["eid_x", "eid_x", "cid_x", "cid_x"]
how would I sort it so it's like this?
let array = ["cid_x", "eid_x", "cid_x", "eid_x"]
The original array is in a random order, example: eid, cid, cid, eid.
Does anyone know how this can be sorted like in the second array?
Split the items into two arrays then grab an item off of one alternating between the two arrays within your loop (or an Array#map in this case).
let array = ["eid_x", "eid_x", "cid_x", "cid_x"]
let eid = array.filter(i => i == 'eid_x')
let cid = array.filter(i => i == 'cid_x')
let result = new Array(array.length).fill(null)
.map((i, idx) => idx % 2 == 0 ? cid.shift() : eid.shift())
console.log(result)

Function that creates an array [duplicate]

This question already has answers here:
How to create an array containing 1...N
(77 answers)
Fastest way to fill an array with multiple value in JS. Can I pass a some pattern or function to method fill insted of a single value in JS? [duplicate]
(1 answer)
Closed 4 years ago.
I want to create a function that takes input from user and returns an array with all the numbers from 1 to the passed number as an argument. Example: createArray(10) should return [1,2,3,4,5,6,7,8,9,10]. I came up with this solution:
function createArray(input) {
var value = 0;
var array = [];
for (i=0;i<input;i++) {
value++;
array.push(value)
console.log(array)
}
}
createArray(12);
What is the correct and better way of doing it?
I would prefer to use Array.from:
const createArray = length => Array.from(
{ length },
// Mapper function: i is the current index in the length being iterated over:
(_, i) => i + 1
)
console.log(JSON.stringify(createArray(10)));
console.log(JSON.stringify(createArray(5)));
There is no need for the extra variable just do this:
function createArray(input) {
var array = [];
for (i = 0; i <= input; i++) {
array.push(i);
}
return array;
}

Javascript reposition array items [duplicate]

This question already has answers here:
Sort an array based on another array of integers
(7 answers)
Closed 7 years ago.
I have an array or numbers and objects (same length):
var a = [2,0,1], b = [obj1,obj2,obj3];
I would like to reposition items in array 'b' to the position of numbers in array 'a'.
Could be done with jquery as well.
How can I do that most easily?
Thanks
To do this there is no an auto function but you can use array map to get this result.
var orderByArray = function(order, data) {
return order.map(function(pos) {
return data[pos];
});
};
var a = [2,0,1];
var b = ['obj1', 'obj2', 'obj3'];
var result = orderByArray(a, b);
console.log('result', result);

Sorting an array in javascript: [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Sort mixed alpha/numeric array
I'm trying to sort an array which contains elements in the form of xxx1, xxx2, xxx3. The Array.sort() method works fine until xxx9 and if there is an element by name xxx10 or xxx11, it fails. The order comes as xxx1, xxx10, xxx11, xxx2 and so on. Please let me know how to fix this.
You are seeing the results of natural string sorting. If string sort is not what you want, you should be using your own comparator.
Do something like:
arrayToBeSorted.sort(function(first,second)
{
/* some code that compares 'first' with 'second' and returns <0, ==0, >0*/
});
At the moment your array is being sorted alphabetically which is why you are getting those results. You need to provide your own comparator function to implement a numerical sort.
Try
var arr = ["xxx1","xxx10","xxx2","xxx20","xxx3","xxx30"];
var sortedArr = arr.sort( function( a, b ) {
// remove first 3 characters so remaining string will parse
a = parseInt( a.substr( 3 ) );
b = parseInt( b.substr( 3 ) );
return a - b;
});
console.log( sortedArr ); // => ["xxx1", "xxx2", "xxx3", "xxx10", "xxx20", "xxx30"]
You can implement custom sorting condition in callback to pass into Array.sort():
​var arr = [],
re = /^\D*(\d+)$/;
for(var i = 20; i-- > 0;) {
arr.push('xxx' + i);
}
function comparator(a, b) {
var numA = a.match(re)[1],
numB = b.match(re)[1];
return numA - numB;
}
arr.sort(comparator);
console.log(arr);
​
http://jsfiddle.net/f0t0n/qz62J/

Categories