How to sum an array of number which contains string in js? - javascript

My array:
const a = [
{
"baseFare": "1439.00",
},
{
"baseFare": "1739.00",
},
{
"baseFare": "1039.00",
},
]
Note: The number of values in const a will increase or decrease its user decisions ! there may be one or 5 or 7 values in the array !
How to sum all the values and output a single value , and in somecase if its only one value then the out put should be direct single value !
How to achive this ?
My code :
a.reduce((a, b) => a + b, 0)

you are almost there
try this,
a.reduce((a, b) => a + (+b.baseFare), 0);
//a is the accumulator , and it start with 0 its an integer
//If you need to access baseFare, then you have to get it from object b.baseFare,
//b.baseFare is a string so you have to convert it to a number (+b.baseFare) is for that
if you really need to get it as a floating point number, for ex: 5000, showing as "5000.00" then try this out
let sum = a.reduce((a, b) => a + (+b.baseFare), 0);;
sum = sum.toFixed(2); //"4217.00"

Just loop, converting the strings to numbers as you go:
let result = 0;
for (const entry of a) {
result += +entry.baseFare;
}
Or with destructuring:
let result = 0;
for (const {baseFare} of a) {
// ^^^^^^^^^^−−−−−−−−−−−−−−−−−−−−− destructuring
result += +baseFare;
}
That unary + is just one way to convert from string to number. I go into all your options in this other answer.

Related

How can I find the sum of an array?

say that I have:
var arr = ['-1254', '+2343']
I want my sum to be 1,089
I tried parseInt(arr.reduce((a, b) => a + b, 0)) but it returns 0.
How can find the sum of arr?
You got 0 because in arr.reduce() initial a value is 0 number type. but b is current value that is '-1245' is string. So that's why it's not calculate.
If you want to calculate it properly you need to make b as an integer. Like this.
var result = arr.reduce((a, b) => a + parseInt(b), 0)
then log this.
Thank you
you need to convert string into number first.
var arr = ['-1254', '+2343']
arr.reduce((a, b) => a *1 + b * 1,0)

Why is my function sometimes squaring twice?

Writing a function to take a number, square each number and return them as a concatenated integer, ie. 3214 => 94116. For some reason, my code appears to occasionally square 2's and 3's twice making a 2 turn into 16 and 3 into 81. I can't figure it out. I'm not a super experienced debugger yet so any help would be appreciated.
function squareDigits(num){
let digits = (""+num).split("");
let intDigits = [];
for (x of digits) {
intDigits.push(parseInt(x));
}
for (x of intDigits) {
intDigits.splice(intDigits.indexOf(x), 1, x * x);
}
return parseInt(intDigits.join(""));
}
console.log(squareDigits(24));
Leaving aside the fact that you can do this more elegantly with something like map() the issue in your code is that it uses indexOf() while changing the values on each iteration. Since indexOf() returns the index of the first occurrence it is going to find digits that you have already replaced.
This is your original code with a few logs so you can understand what I mean:
function squareDigits(num){
let digits = (""+num).split("");
let intDigits = [];
for (x of digits) {
intDigits.push(parseInt(x));
}
for (x of intDigits) {
console.log('intDigits: ' + intDigits);
console.log(` index of ${x} = ${intDigits.indexOf(x)}`);
intDigits.splice(intDigits.indexOf(x), 1, x * x);
}
return parseInt(intDigits.join(""));
}
console.log('RESULT: ' + squareDigits(24));
Notice how in the second pass the index of 4 is 0 (the first position in the array) because you have replaced the original 2 by it's squared value 4.
A simple way to fix this is to not rely on indexOf() and iterate over the array the good old way, like this:
function squareDigits(num){
let digits = (""+num).split("");
let intDigits = [];
for (x of digits) {
intDigits.push(parseInt(x));
}
for (let i = 0; i < intDigits.length; i++) {
const x = intDigits[i];
console.log('intDigits: ' + intDigits);
console.log(` index of ${x} = ${i}`);
intDigits.splice(i, 1, x * x);
}
return parseInt(intDigits.join(""));
}
console.log('RESULT: ' + squareDigits(24));
A simplistic (and bug free) version of your function could be this:
const squareDigits = num => [...num.toString()].map(x => x ** 2).join('');
console.log(squareDigits(24));
Other variant:
const squareDigits = num => num.toString().replaceAll(/\d/g, x => x ** 2);
console.log(squareDigits(24));
Instead of looping twice use array methods .map() , .reduce() etc it will make your code effective .. wrote a simple function
See =>
function squareDigits(num){
let digits = String(num).split("");
digits = digits.reduce((final , digit)=> final += String( parseInt(digit) **2 ), "");
return digits
}
console.log(squareDigits(312));
As #Sebastian mentioned, intDigits.indexOf(x) will find the
first index. So after replacing the first one, there's a change you'll find the number you've just replaced.
We can simplify the function to :
function squareDigits(num){
return num.toString().split('').map(n => n ** 2).join('');
}
Where :
We convert the number to a string using toString()
We split the string into loose numbers using split('')
map() over each number
Return the square by using the Exponentiation (**) operator
join() the numbers to get the result
Example snippet:
function squareDigits(num){
return num.toString().split('').map(n => n ** 2).join('');
}
console.log(squareDigits(3214)); // 94116

Multiplying digits within a number - excluding zeros

I have function taken from this example here that works well, except does not address any zeros that may be in the number, so everything is equaling zero when executing the function.
Multiplying individual digits in a number with each other in JavaScript
function digitsMultip(data) {
let arr = [];
for (let i of data) {
if (data[i] === 0) {
arr.push(data[i]);
}
}
return [...data.toString()].reduce((p, v) => p * v);
};
console.log(digitsMultip(3025));
I added to it a for-loop that accounts for the zero and remove it, but im doing something wrong here.
Uncaught TypeError: data is not iterable
DESIRED OUTPUT
3025 => 3 * 2 * 5 = 30
This iterates over the characters in your number. If the character is not "0" then it is added to the array. This array is then reduced by multiplying the values and then returned.
function digitsMultip(data) {
const arr = [];
for(let number of String(data)) {
if (number !== "0")
arr.push(number);
}
return arr.reduce((p, v) => p * v);
};
console.log(digitsMultip(3025));
You are getting that error because you are trying to iterate over a number.
Passing in a string or converting the number to string before iterating it would make it work.
Instead of looping it that way, a better and readable way would be to use the filter method to filter out the chars before multiplying:
function digitsMultip(data) {
return [...data.toString()].filter(n => n > '0').reduce((p, v) => p * v);
};
console.log(digitsMultip(3025));
Turn the input into a string, then split, filter the zeros and reduce multiplying
const input = 1203
const removeZeros = number =>{
const arr = number.toString().split('').filter(i => i !== '0')
return arr.reduce((a,c) => parseInt(a) * parseInt(c))
}
console.log(removeZeros(input))
One line version
const removeZeros = n => [...n.toString()].filter(c => c !== '0').map(x => parseInt(x)).reduce((a,c) => a*c)

How to get a random number without duplicate digits in JavaScript/jQuery?

Update: The number can be started with zero.
I want to have a function like
function getRandomNumber(n){
...
}
I hope it gets a number with n digits while none of the digits is repeated. For instance:
getRandomNumber(3) -> 152 is what I want.
getRandomNumber(1) -> 6 is what I want.
getRandomNumber(6) -> 021598 is what I want. It can start with zero.
getRandomNumber(5) -> 23156 is what I want.
getRandomNumber(3) -> 252 is not because it has two 2.
getRandomNumber(5) -> 23153 is not because it has two 3.
Any simple way to do this?
On each call, make an array of digits, and then repeatedly pick random values and remove them from said array:
function getRandomNumber(n){
const digits = Array.from({ length: 10 }, (_, i) => i);
const result = Array.from({ length: n }, () => {
const randIndex = Math.floor(Math.random() * digits.length);
const digit = digits[randIndex];
digits.splice(randIndex, 1);
return digit;
});
return Number(result.join(''));
}
Array.from({ length: 10 }, () => console.log(getRandomNumber(8)));
By keeping an array as an hash map, an efficient solution is as follows. However keep in mind that unless it's a string a number can not start with 0.
function getRandomNumber(n){
var a = [],
x = ~~(Math.random()*10),
r = 0;
while (n) {
a[x] === void 0 && (a[x] = true, r += x*Math.pow(10,n-1), --n);
x = ~~(Math.random()*10);
}
return r;
}
console.log(getRandomNumber(3));
console.log(getRandomNumber(4));
console.log(getRandomNumber(5));
console.log(getRandomNumber(6));
console.log(getRandomNumber(7));
Don't how to deal with javascript but if it can help you, here a line of scala doing the job
def obtainRestrictedRandomNumber(): Long = scala.util.Random.shuffle((0 to 9)).mkString("").toLong
What it does is simply generating all digits from 0 to 9 then randomize them, concatenate the Array Int elements into a string for finally casting it into a Long.

How to sort set of numbers both lexicographically and numerically?

I currently have a set of strings that are both just numbers and number with + or -. Such as follows :
1 , 1+, 1-, 2, 2+, 2-, 10
Which when I sort using JavaScript's sort functions gives out:
1, 1+ , 1-, 10, 2, 2+, 2-
which is lexicographically orders but not numerically. Is there a way to sort this so the numbers come out in the correct way(the first list) ? I am using ExtJS stores so an answers as a store sorter is preferred but plain javascript is also fine. Thanks ?
Edit: This is not just sorting numbers.
You can use a custom ordering function like so:
var numbers = ['1', '1-', '1+', '2', '2+', '2-', '10'];
numbers.sort(function (a, b){
var _a = parseFloat(a), // If the values are integers only, parseInt will do too
_b = parseFloat(b);
if (_a - _b === 0) {
return (a > b) ? 1 : -1;
} else {
return _a - _b;
}
});
console.log(numbers);
The function checks whether the number values are equal, and if so, falls back to lexicographic ordering to sort the character suffixes. If there are no suffixes in equal-case, hence no matter in which order the numbers are returned. If only one of the operands has a suffix, bare number returns negative. If the number values are not equal, the function simply returns the tristate, i.e a - b, which will be evaluated to one of negative, 0, positive. Or actually it's "bistate", since we've handled 0 case already.
More generic solution
The code above is rather a special case for two different single charactered suffixes only. If suffixes are more complex, here's a more generic code to sort by number and by suffixes:
var numbers = ['1', '1-r', '1+q', '1', '2', '2+q', '2-r', '10'];
function suffixSort (suff, asc) {
asc = 2 * +(!!asc) - 1; // Convert boolean to -1 or 1
return function (a, b) {
var _a = parseFloat(a), // Extract the number value
_b = parseFloat(b),
aSI = -(a.length - _a.toString().length), // Get the index of suffix start
bSI = -(b.length - _b.toString().length);
// Equal number values, sort by suffixes
if (_a === _b) {
return (suff.indexOf(a.substr(aSI)) > suff.indexOf(b.substr(bSI))) ? 1 : -1;
}
// Inequal number values, sort by numbers
return asc * (_a - _b);
}
}
// suffixSort arguments
// suff: An array of the suffix strings to sort, ordered in the desired sorting order
// asc: true = ascending, false = descending. Optional, defaults to descending sort
numbers.sort(suffixSort(['+q', '-r'], true));
console.log(numbers);
The idea is to store the suffixes into an array, and when suffix sorting is needed, function compares the array indices of the suffixes instead of the suffixes themselves.
suffixSort lets you also to decide the sorting direction. Selected sorting direction doesn't have an effect on suffix sorting, they are always returned in the order they appear in suff array.
These values are almost integers, so comparing them according to praseInt will almost get you there. The only thing missing is a special treatment for values that have the same integer part where x- should come first, then x and finally x+:
function specialChar(s) {
c = s.substr(-1);
if (c == '+') {
return 1;
}
if (c == '-') {
return -1;
}
return 0;
}
function numCompare(a, b) {
aNum = parseInt(a);
bNum = parseInt(b);
cmp = aNum - bNum;
if (cmp != 0) {
return cmp;
}
// Integer parts are equal - compare the special char at the end
return specialChar(a) - specialChar(b);
}
arr = ['1' , '1+', '1-', '2', '2+', '2-', '10'];
arr.sort(numCompare);
var result=[];
result=array.map(function(n){
if(typeof n==='number') return n;
if(n[n.length-1]=='+'){
return parseInt(n.substring(0,n.length-1))
}
else if(n[n.length-1]=='-'){
return 0-parseInt(n.substring(0,n.length-1))
}
});
result.sort(function(a,b){return a-b})
You could use Array#sort and split the elements in numbers and the rest, then return the difference or the difference of the order.
var array = ['10', '2', '2+', '2-', '1', '1+', '1-'];
array.sort(function (a, b) {
var r = /\d+|\D+/g,
aa = a.match(r),
bb = b.match(r),
order = { '+': 1, '-': 2 };
return aa[0] - bb[0] || (order[aa[1]] || 0) - (order[bb[1]] || 0);
});
console.log(array);
If there are only three possible states of a number, and the states have the order number, number+, number the states can be recreated by creating an array representation of the numbers, removing the unique numbers from array, from minimum to maximum, concatenating empty string or arithmetic operator in required order to the number, then pushing the value to an array, where .toString() can be used to view the comma separated string representation of the sorted values within the array
var str = `314+, 1-, 7+, 1, 1-, 271-, 10-
, 10+, 271, 271+, 314-, 314
, 10, 2-, 2, 2+, 7-, 7`;
for (var [nums, order, res, num] = [str.match(/\d+/g), ["", "+", "-"], [], null]
; nums.length
; num = Math.min.apply(Math, nums)
, res = [...res, ...order.map(op => num + op)]
, nums = nums.filter(n => n != num)
);
console.log(res.toString() + "\n", res);
Assuming that you just want to throw away the symbols, then you could use parseInt and Array#sort to get order numerically.
var data = ['1' , '1+', '1-', '2', '2+', '2-', '10'];
var sortedData = data.sort(function(a,b){return parseInt(a)-parseInt(b);});

Categories

Resources