How to change multiple values in the array JavaScript - javascript

I have an array created with a for loop that has 50 values.
var array = [];
array [0] = {
selection : 0
}
var number = 1;
for (i = 0; i < 50; i++){
array[i].selection = number;
number ++;}
How to change the value for the array[i-20].selection? I don't want to use array[30].selection
It usually works if use array[i-1].selection or array[i+1].selection but doesn't work if use anything greater than one.
Thanks

You wanted Array of Objects and not Array with single Object, right ?
var array = [];
var number = 1;
fillFrom(3, 1); // should push instead of setting and start from zero but ;-)
var res = '<table width=1><tr><td>' + JSON.stringify(array).replace(/,/g, ',<br>') + '</td>';
fillFrom(0, -49);
res += '<td>' + JSON.stringify(array).replace(/,/g, ',<br>') + '</td></tr></table>';
document.body.innerHTML = res;
function fillFrom(start, number) {
for (i = start; i < 50; i++) {
if (array[i] === undefined) array[i] = {
selection: number
};
else array[i].selection = number;
number++;
}
}

Related

Inserting a Value without splice or push command

I am currently working on some code to insert user inputted variables into an array at a specified point WITHOUT using the splice or the push command. I decided to try to use a while command as that is what makes the most sense to me as I am very new to javascript. When I do try to display nothing comes up.
var array = []; // Flobal array to hold array
var d = ""; // Global string for output
function fillArray() {
// call function to clear the display values
clearDisplay();
// simple loop hard coded to 100 to set array values
for (var i = 0; i < 100; i++) {
array[i] = Math.floor(Math.random() * 100 + 1);
}
// call function to display the array
displayArray();
}
function clearDisplay() {
//Global string d is used to hold display
d = "";
// The div element named output is used to display output
document.getElementById("output").innerHTML = "";
}
function displayArray() {
// simple loop to add array values to string d
for (var i = 0; i < array.length - 1; i++) {
d += i + ' : ' + array[i] + "<br/>";
}
document.getElementById("output").innerHTML = d;
}
//-------------------------------------------------------
//Scan array and insert into index
function insertArray() {
var m = parseInt(document.getElementById("index").value);
var n = parseInt(document.getElementById("value").value);
while (i < m) {
i++;
}
if (i == m) {
array[i] == n;
}
displayArray();
}
Possible solution is to create new array every time and overwrite old one. We create two counters one for old array, second for new array. While coping items from old array to new one, when we'r at desired index we'r adding desired value from input and increases only new array counter.
function insertArray() {
var m = parseInt(document.getElementById("index").value);
var n = parseInt(document.getElementById("value").value);
var c = 0, o = 0, l = array.length + 1, new_array = [];
while (c < l) {
if (c === m) {
new_array[c] = n;
} else {
new_array[c] = array[o];
o++;
}
c++;
}
array = new_array;
clearDisplay();
displayArray();
}
var array = []; // Flobal array to hold array
var d = ""; // Global string for output
function fillArray() {
// call function to clear the display values
clearDisplay();
// simple loop hard coded to 10 to set array values
for (var i = 0; i < 10; i++) {
array[i] = Math.floor(Math.random() * 100 + 1);
}
// call function to display the array
displayArray();
}
function clearDisplay() {
//Global string d is used to hold display
d = "";
// The div element named output is used to display output
document.getElementById("output").innerHTML = "";
}
function displayArray() {
// simple loop to add array values to string d
for (var i = 0; i < array.length; i++) {
d += i + " : " + array[i] + "<br/>";
}
document.getElementById("output").innerHTML = d;
}
fillArray();
//-------------------------------------------------------
//Scan array and insert into index
function insertArray() {
var m = parseInt(document.getElementById("index").value);
var n = parseInt(document.getElementById("value").value);
var c = 0, o = 0, l = array.length + 1, new_array = [];
while (c < l) {
if (c === m) {
new_array[c] = n;
} else {
new_array[c] = array[o];
o++;
}
c++;
}
array = new_array;
clearDisplay();
displayArray();
}
<p>Output: </p>
<input type="text" id="index">
<input type="text" id="value">
<button onClick="insertArray();">Insert</button>
<hr>
<div id="output">
</div>
You can use the following code to add elements to an array without using the splice or push command at the given index. See the implementation of insertArray function, I have commented out the wrong code and written a new line.
var array = []; // Flobal array to hold array
var d = ""; // Global string for output
function fillArray() {
// call function to clear the display values
clearDisplay();
// simple loop hard coded to 100 to set array values
for (var i = 0; i < 100; i++) {
array[i] = Math.floor(Math.random() * 100 + 1);
}
// call function to display the array
//displayArray();
}
function clearDisplay() {
//Global string d is used to hold display
d = "";
// The div element named output is used to display output
document.getElementById("output").innerHTML = "";
}
function displayArray() {
// simple loop to add array values to string d
for (var i = 0; i < array.length - 1; i++) {
d += i + ' : ' + array[i] + " ";
}
document.getElementById("output").innerHTML = d;
}
//-------------------------------------------------------
//Scan array and insert into index
function insertArray() {
var m = parseInt(document.getElementById("index").value);
var n = parseInt(document.getElementById("value").value);
var temp = array[m];
array[m] = n;
for (var i = m+1; i < 100; i++) {
array[i] = temp;
temp = array[i];
}
/*
while (i < m) {
i++;
}
if (i == m) {
array[i] = n;
}
*/
displayArray();
}
fillArray();
<p>Output: </p>
<input type="text" id="index">
<input type="text" id="value">
<button onClick="insertArray();">Insert</button>
<hr>
<div id="output">
</div>
Please let me know if this is what you wanted.

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

JavaScript Total Returns NaN

I am trying to sum an array of objects using JavaScript, but instead of displaying the expected outcome of 86 it displays NaN.
Note: I am not able to edit the array of objects!
var objects = [{"ID":"--"},{"ID":"58"},{"ID":"28"}];
var sum = 0;
id = objects;
for (var i = 0; i < id.length; i++) {
sum += +id[i].ID;
}
document.getElementById('here').innerHTML = "<b>Total:</b>" + sum;
objects.forEach(function(key) {
var a = document.createElement("p");
a.innerHTML = key.ID;
document.getElementById('here').appendChild(a);
});
<div id="here"></div>
JsFiddle: https://jsfiddle.net/ru266x7m/
Please be aware that this is not a duplicate of Object returning NaN when sum values as I already have the line of code var sum = 0;
You could insert a check if the value isFinite.
if (isFinite(id[i].ID)) {
sum += +id[i].ID;
}
var objects = [{"ID":"--"},{"ID":"58"},{"ID":"28"}];
var sum = 0;
id = objects;
for (var i = 0; i < id.length; i++) {
if (isFinite(id[i].ID)) {
sum += +id[i].ID;
}
}
document.getElementById('here').innerHTML = "<b>Total: </b>" + sum;
objects.forEach(function(key) {
var a = document.createElement("p");
a.innerHTML = key.ID;
document.getElementById('here').appendChild(a);
});
<div id="here"></div>
your very first data point is {"ID":"--"}
you can't add -- and get an integer from it.
"--" + 1 is NaN
if you want this to return an actual number, you must add actual numbers
update
if you need to check the values, use parseInt and isNaN inside of your loop
var value = parseInt(id[i].ID. 10);
var valid = isNaN(value);
if (valid){
sum += value;
}
An optimized version using Number constructor, isNan function and documentFragment(making only one loop instead of two):
var objects = [{"ID":"--"},{"ID":"58"},{"ID":"28"}];
var sum = 0, hereEl = document.getElementById('here'),
f = document.createDocumentFragment();
objects.forEach(function(key) {
var p = document.createElement("p"), num = Number(key.ID);
p.innerHTML = key.ID;
sum += !isNaN(num)? num : 0;
f.appendChild(p);
});
hereEl.innerHTML = "<b>Total:</b>" + sum;
hereEl.appendChild(f);
<div id="here"></div>
You can check validity of any value with isNaN type check (means is Not a Number). Type checker will return false if ID is number or string number.
var objects = [{"ID":"--"},{"ID":"58"},{"ID":"28"}];
var sum = objects.reduce((s, o) => console.log(o.ID) || s + (isNaN(o.ID) ? 0 : +o.ID), 0);
console.log('Total: ' + sum);

Adding a dash between 2 even numbers after printing out randomly generated numbers in array

So I've been trying to add a dash between every even number, but it's not outputting the dash. What am I doing wrong?
Generating 20 random numbers and putting them into array
var i = 0;
mainarr = [];
do {
mainarr[i]=parseInt(Math.random()*10);
i++;
}
while (i<20);
Printing the 20 numbers and adding dashes between every even number
var endVal =20;
for (i=0; i< endVal ;)
{
main.innerHTML += mainarr[i];
if ((i%2)==0) {
i++;
if ((i % 2)==0)
main.innerHTML += "-";
}
else
i++;
}
Here is how I would do it, using a temporary variable to store whether or not the last value was even, and comparing it against the current value.
var length = mainarr.length,
lastNumberEven = false,
thisNumberEven,
tmpString = '';
for (i = 0; i < length; i++) {
if ((thisNumberEven = mainarr[i] % 2 == 0) && lastNumberEven) {
tmpString += '-';
}
tmpString += mainarr[i];
lastNumberEven = thisNumberEven;
}
main.innerHTML = tmpString;

Append to each element in an array in Javascript

With an array, how would I append a character to each element in the array? I want to add the string ":" after each element and then print the result.
var a = [54375, 54376, 54377, 54378, 54379, 54380, 54381, 54382, 54383, 54384, 54385, 54386, 54387, 54388, 54389, 54390, 54391, 54392, 54393, 54394, 54395, 54396, 54397, 54400, 54402, 54403, 54405, 54407, 54408];
For example: 54375:54376:54377
a = a.map(function(el) { return el + ':'; });
Or if you want to join them into a string:
var joined = a.join(':');
If you are looking for a way to concatenate all the elements with :, you can use this
var result = "";
for (var i = 0; i < a.length; i += 1) {
result += a[i] + ":";
}
result = result.substr(0, result.length-1);
Or even simpler, you can do
a = a.join(":");
If you are looking for a way to append : to every element, you can use Array.prototype.map, like this
a = a.map(function (currentItem) {
return currentItem + ":";
});
console.log(a);
If your environment doesn't support map yet, then you can do this
for (var i = 0; i < a.length; i += 1) {
a[i] = a[i] + ":";
}

Categories