How can I find the sum of an array? - javascript

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)

Related

How to sort a dash-seperated range of numbers?

I have a range of numbers as follows:
const a = ["11-50", "2-10", "1", "51-200"]
I would like to sort them properly like
["1", "2-10", "11-50", "51-200"]
I have tried both of these sort methods to no avail:
a.sort((a, b) => a - b)
a.sort()
We can try sorting on the lower bound number in each range:
const input = ["11-50", "2-10", "1", "51-200"];
input.sort(function(a, b) {
return parseInt(a.split("-")[0]) - parseInt(b.split("-")[0]);
});
console.log(input);
Disclaimer: parseInt may not always do what you want, but with this example it should work!
a.sort((a, b) => parseInt(a) - parseInt(b));
A little more formally, write some code to change representation from strings to numbers and back...
const string2Range = string => string.split('-').map(parseInt);
const range2String = range => `${range[0}-${range[1]}`;
Define what makes a range smaller than another...
// low value?
const compLow = (rangeA, rangeB) => rangeA[0] - rangeB[0]
// midpoint value?
const midpoint = range => (range[1] - range[0]) / 2;
const compMid = (rangeA, rangeB) => midpoint(rangeA) - midpoint(rangeB);
// something else??
Then transform, sort, transform back (assuming string output is desired)
let input = ["11-50", "2-10", "1", "51-200"]
let ranges = input.map(string2Range);
ranges.sort(compLow); // or another you define
let output = ranges.map(range2String)
You could match numbers and if two numbers are available, take it for an adjusted sort.
Try this snippet-
a = ["11-50", "2-10", "1", "51-200"]
a.sort(function (a, b) {
function getV(v) { return v.match(/\d+/g); }
var aa = getV(a),
bb = getV(b);
return aa[0] - bb[0] || (aa[1] || aa[0]) - (bb[1] || bb[0]);
});
console.log(a)

Javascript reduce method not returning expected output. What is going wrong here?

I am working on a codeWars challenge and am unsure why my reduce method isn't returning the expected outcome.
Here are the instructions:
A Narcissistic Number is a number of length n in which the sum of its digits to the power of n is equal to the original number. If this seems confusing, refer to the example below.
Ex: 153, where n = 3 (number of digits in 153)
1³ + 5³ + 3³ = 153
Write a method is_narcissistic(i) which returns whether or not i is a Narcissistic Number.
Here is my solution:
function narcissistic(value) {
let digits = (value + '').split('').map(Number);
let narc = digits.reduce((a, c) => a + (c ** digits.length))
return narc === value;
}
console.log(narcissistic(371))
When I test it with 371, which is a narcissistic number, 341 is returned instead of 371
If you don't supply an initial value, the 1st item is used as the initial value, and it's not multiplied. Set the initial value to be 0.
function narcissistic(value) {
let digits = (value + '').split('').map(Number);
let narc = digits.reduce((a, c) => a + (c ** digits.length), 0)
return narc === value;
}
console.log(narcissistic(371))

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

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

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.

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)

Categories

Resources