User Input is not storing correctly in array - javascript

Im given the task of storing 10 elements in an Array, then I have to add all of those elements.
My problem comes at the time of storing each individual element in the array.
When I set the length of the for loop as numbers.length it fills the array with the first number that was inputted, and if I set the length to 10, it only places the value in the index[0] and leaves the others as undefined.
var numbers = new Array();
function addnew() {
var un = document.getElementById('userNumber').value;
for (var i = 0; i < 10; i++) {
numbers.push(" " + un[i]);
}
console.log(numbers);
document.getElementById('elements').innerHTML = numbers;
The output that is expected is a list that shows the values entered by the user inputs into the array (length of 10) and the sum of those values.
What it's actually showing is the first number inputted followed by undefined till it reaches the maximum length which is 10.

it's because un string length is 1 as it not saved completely
var numbers = new Array();
function addnew() {
var un = '123';
for (var i = 0; i < Math.min(10,un.length); i++) {
numbers.push(" " + un[i]);
}
console.log(numbers);
document.getElementById('elements').innerHTML = numbers;
}
}

If your user is entering a space inbetween each number, you can just split that one string into an array.
numbers = un.split(" ");
numbers now contains an array of strings.
Then convert the strings to numbers, so you can get the sum.
for (var i = 0; i < numbers.length; i++) {
numbers[i] = Number(numbers[i]);
}
And then this will give you the sum.
sumOfNumbers = numbers.reduce((a, b) => a + b, 0);
console.log(sumOfNumbers);
un = "1 2 3 12";
numbers = un.split(" ");
console.log(numbers);
for (var i = 0; i < numbers.length; i++) {
numbers[i] = Number(numbers[i]);
}
console.log(numbers);
sumOfNumbers = numbers.reduce((a, b) => a + b, 0);
console.log("sum is " + sumOfNumbers);

At beginning your numbers.length is 0. I think you should do un.length
function addnew() {
var numbers = [];
var un = document.getElementById('userNumber').value;
for (var i = 0; i < un.length; i++) {
numbers.push(" " + un[i]);
}
console.log(numbers);
document.getElementById('elements').innerHTML = numbers;
}
<input type="text" id="userNumber" onChange="addnew()"/>
<span id="elements"></span>

Related

Javascript for loop not iterating across array or values in an if statement not updating as planned

Trying to return the highest 5 digit number out of any given number i.e 34858299999234
will return 99999
I think I have it narrowed down to the for loop not iterating the array properly OR the values for 'hold1' and 'hold2' are not updating.
function solution(digits){
//Convert string to array to iterate through
let arr = digits.split("");
let final = 0;
//iterate through the array in 5 sequence steps
for(let i = 0; i < arr.length-1; i++){
let hold1 = arr[i] + arr[i+1] + arr[i+2] + arr[i+3] + arr[i+4];
hold1 = parseInt(hold1,10); //converting string to int so if statement functions correctly
let hold2 = arr[i+1] + arr[i+2]+ arr[i+3] + arr[i+4] + arr[i+5];
hold2 = parseInt(hold2,10);
if(hold1 >= hold2){
final = hold1;
}else{
final = hold2;
}
return final;
}
}
if you need a five digits result you need to change the for loop in something like this:
for (let i = 0; i < arr.length - 5; i++) {
Otherwise you will generate results shorter than 5 digits.
Also, I think you are missing the Math.max method that will compare two numbers to return the bigger one.
I rewrote your function this way:
function solution(digits) {
let op = 0;
let length = 5;
let stringDigits = String(digits); /// <-- I use string instead of array
if (stringDigits.length <= length) {
return digits; /// <-- If input is shorter than 5 digits
}
for (let i = 0; i < stringDigits.length - length; i++) {
const fiveDigitsValue = stringDigits.substr(i, length);
op = Math.max(op, Number(fiveDigitsValue));
}
return op;
}

Finding the sum of a "counter" variable loop that ran ten times then was pushed into the "numbers" array. Each way I tried resulted with a list

I'm asking for help to find the sum of an array with elements that were pushed from a counter variable that had previously looped 10 times. I'm new to Javascript and was practicing for an assessment, and I've tried several different ways to do it and have only resulted with just a list of the elements within the numbers array.
var counter = 10;
var numbers = [];
for (i = 1; i <= 10; i ++) {
counter = [i + 73];
numbers.push(counter);
}
console.log(numbers);
function sum(arr) {
var s = 0;
for(var i = 0; i < arr.length; i++) {
s = s += arr[i];
}
return s;
}
console.log(sum([numbers]));
function getArraySum(a) {
var total = 0;
for (var i in a) {
total += a[i];
}
return total;
}
var numbers = getArraySum([numbers]);
console.log(numbers);
you should push only the value of counter without the brackets and then make a reduce to have the sum of each number in the array
var counter = 10;
var numbers = [];
for (i = 1; i <= 10; i++) {
counter = i + 73;
numbers.push(counter);
}
console.log(numbers.reduce((a,b) => a+b));
You had a couple of typos in the code:
Typos
You were wrapping the sum in square brackets:
counter = [i + 73];
You should just remove the brackets like:
counter = i + 73;
2. You were wrapping a value that is already an array in square brackets while passing it as an argument to a function:
sum( [numbers] )
// ...
getArraySum( [numbers] );
You should remove the brackets, like this:
sum( numbers );
// ...
getArraySum( numbers );
Fix
I updated the code that you shared to fix the above-mentioned things:
var numbers = [];
// Loop 10 times and push each number to the numbers array
for (var i = 1; i <= 10; i ++) {
var sumNumbers = i + 73;
numbers.push(sumNumbers);
}
console.log(numbers);
function sum(arr) {
var total = 0;
for(var i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
}
// Call the function by passing it the variable numbers, holding an array
var result1 = sum(numbers);
console.log( result1 );
function getArraySum(a) {
var total = 0;
for (var i in a) {
total += a[i];
}
return total;
}
var result2 = getArraySum(numbers);
console.log(result2);

Splitting Numbers and adding them all - JavaScript

I have a function that returns the sum of all its digits For both POSITIVE and NEGATIVE numbers.
I used split method and converted it to string first and then used reduce to add them all. If the number is negative, the first digit should count as negative.
function sumDigits(num) {
var output = [],
sNum = num.toString();
for (var i = 0; i < sNum.length; i++) {
output.push(sNum[i]);
}
return output.reduce(function(total, item){
return Number(total) + Number(item);
});
}
var output = sumDigits(1148);
console.log(output); // --> MUST RETURN 14
var output2 = sumDigits(-316);
console.log(output2); // --> MUST RETURN 4
Instead of returning the sum, it returned 4592 -1264
Am I doing it right or do I need to use split function? Or is there any better way to do this?
Sorry newbie here.
I think you'll have to treat it as a string and check iterate over the string checking for a '-' and when you find one grab two characters and convert to an integer to push onto the array. Then loop over the array and sum them. Of course you could do that as you go and not bother pushing them on the array at all.
function sumDigits(num) {
num = num + '';
var output = [];
var tempNum;
var sum = 0;
for (var i = 0; i < num.length; i++) {
if (num[i] === '-') {
tempNum = num[i] + num[i + 1];
i++;
} else {
tempNum = num[i];
}
output.push(parseInt(tempNum, 10));
}
for (var j = 0; j < output.length; j++) {
sum = sum + output[j];
}
return sum;
}
var output = sumDigits(1148);
console.log(output); // --> MUST RETURN 14
var output2 = sumDigits(-316);
console.log(output2); // --> MUST RETURN 4

Iterating through a number and rearranging in descending

I'm trying to rearrange an input number using a function so that a single number is rearranged into descending order.
For example, 234892 would result in 984322.
This is what I have come up with.
function descendingOrder(n){
var num = '';
for(var i = 0; i <= n.length + 1; i++){ // iterates through the number
for(var j = 9; j >= 0; j--){ // starts at 9 and checks numbers descending
if (j == n[i]){
num.push(n[i]); // checks if j == n[i] and if so, pushes to num
}
i = 0; // sets i back to 0 to rescan the number again
}
}
return num;
}
You can convert number to string, split each character, sort it and join it again:
+(234892 + '').split('').sort((a, b) => a < b).join('');
var ordered = +(234892 + '').split('').sort((a, b) => a < b).join('');
document.getElementById('output').appendChild(document.createTextNode(ordered));
234892 → <span id="output"></span>
Detailed explanation:
var str = 234892 + ''; // convert to string
var parts = str.split(''); // convert to array of characters
// sort
parts.sort(function(a, b) {
return a < b;
});
var finalStr = parts.join(''); // join characters to string
var finalNumber = +finalStr; // convert back to number
console.log(finalNumber); // 984322

Combinations of numbers in array who sum is equal to n

Example:
var a = [1,2,3,4,5,6];
I want to display all of the unique 3 number combinations in the array where the sum of those 3 digits is equal to 9 (or n).
So result in this example would be:
[1,2,6]
[2,3,4]
[1,3,5]
Closest thing I could find was permutations of a string...
var alphabet = "abcde"; // shortened to save time
function permute(text) {
if(text.length === 3) { // if length is 3, combination is valid; alert
console.log(text); // or alert
} else {
var newalphabet = alphabet.split("").filter(function(v) {
return text.indexOf(v) === -1;
}); // construct a new alphabet of characters that are not used yet
// because each letter may only occur once in each combination
for(var i = 0; i < newalphabet.length; i++) {
permute(text + newalphabet[i]); // call permute with current text + new
// letter from filtered alphabet
}
}
}
permute("");
This could be a possible solution. Please note it does not take care of unique values and for that you need to add additional logic. However, if the array is sorted and have unique entries then the following will be producing the ideal result.
var a = [1,2,3,4,5,6];
var result = [];
for (var i = 0; i < a.length-2; i++) {
for (var j = i+1; j< a.length-1;j++) {
for (var k = j+1; k < a.length;k++) {
if(a[i]+a[j]+a[k] == 9) {
result.push([a[i],a[j], a[k]]);
}
}
}
}
console.log(result);

Categories