I am getting a wrong ouput, i am storing a value greater than 400 in an array arr[] I want to store the values 450, 650 in my arr[] and my arr[] length should be 2(two) since there are two values greater than 400, but I am getting a wrong output.
array length value inside array
var total = [300, 350, 450, 650];
var arr = [];
for (var i = 0; i < total.length; i++) {
if (parseInt(total[i]) >= 400) {
arr[i] = total[i];
}
}
alert(arr.length);
alert(arr);
5 Answers 5
You are defining array elements by an index which leads to the array with some undefined values(undefined index within the larger index defined). Instead use Array#push to add array elements in the proper way.
arr.push(total[i]);
5 Comments
length property just won't be in sync with the actual number of elements in itif (parseInt(total[i]) >= 400) { arr[i] = total[i]; }arr from OP, you can see it contains 2 elements (450 and 650). No undefined values, only missing elements and a length proprety that is not in sync. See this jsfiddle , at beginning :)0 n 1 is not defined....You add the total value at the index "i" to the arr index "i". But the arr has not the same index as total.
so you need to do this:
var total = [300, 350, 450, 650];
var arr = [];
for (var i = 0; i < total.length; i++) {
if (parseInt(total[i]) >= 400) {
arr.push(total[i]);
}
}
alert(arr.length);
alert(arr);
Comments
Your code is a bit wrong , I am correcting it:
var total = [300, 350, 450, 650];
var arr = [];
for (var i = 0; i < total.length; i++) {
if (parseInt(total[i]) >= 400) {
arr.push(total[i]);
}
}
alert(arr.length);
alert(arr);
Comments
Use ECMA6, and it is a lot easier to read
var total = [300, 350, 450, 650];
var arr = total.filter(value => value >= 400);
console.log(arr.length);
console.log(arr);
and otherwise
var total = [300, 350, 450, 650];
var arr = [];
for (var i = 0; i < total.length; i++) {
if (parseInt(total[i]) >= 400) {
arr.push(total[i]);
}
}
alert(arr.length);
alert(arr);
With this part of code arr[i] = total[i]; you add each time the value to the same position as the original position. The other values lower than 400 will not be added but will be mapped as empty values
Comments
You should have a counter to accomplish your task
var total = [300, 350, 450, 650];
var arr = [];
var counter=0;
for (var i = 0; i < total.length; i++) {
if (parseInt(total[i]) >= 400) {
arr.push(total[i]); //to save into an array
}
}
console.log(arr.length);
arrarray instead of assigning via thearr[i]