Adding values to an array in JavaScript loops [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm learning JavaScript and I used the loops to add some values to an array and then print theme and see the result. I have done this with different methods but I have a problem with one of them.
In the code below I can't think of a way to add values to an array using for/in the loop. How can I do this?
<script type="text/javascript">
function print(string){
document.write(string+"<br>");
}
</script>
<script type="text/javascript">
print("with for & for..in");
var ma1Arr = [];
for (i = 10; i < 20; i++) {
ma1Arr.push(i);
}
for (i in ma1Arr) {
print(ma1Arr[i]);
}
print("<hr>");
print("with for & for..in vice versa");
var ma3Arr = [];
i=20;
for (i in ma3Arr){
ma3Arr.push(i);
i++
}
for (i=0; i<ma3Arr.length; i++){
print(ma3Arr[i])
}
print("<hr>");
print("with while & do..while");
var ma2Arr = [];
i = 30;
do {
ma2Arr.push(i);
i++;
} while (i < 40);
i = 0;
while (i < ma2Arr.length) {
print(ma2Arr[i]);
i++;
}
print("<hr>");
print("with while & do..while vice versa");
var ma4Arr = [];
i = 40;
while (i<=50){
ma4Arr.push(i);
i++;
}
i = 0
do {
print(ma4Arr[i]);
i++;
}while (i<ma4Arr.length);
</script>

for...in is used for objects like {a: 1, b: 4} and not for arrays. It is iterating all enumerable properties of the object such as a and b. But for arrays, you would need to go with for...of
for..in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
for...of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

var array_name = [item1, item2, ...];
You put the values inside of the brackets... That is basically how you make an array for any language

Related

How to use the for loop in this situation [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have data like this:
data = [
{ 'name':'suresh', 'age':25}
{ 'name':'ramesh', 'age':35}
{ 'name':'raina', 'age':15}
]
I have tried like
for(let ele in data){
consolelog(ele)
}
Current Output
0
1
2
Expected Output
{ 'name':'suresh', 'age':25}
{ 'name':'ramesh', 'age':35}
{ 'name':'raina', 'age':15}
You have to use the of keyword for looping arrays
for(let ele of data){
console.log(ele)
}
It's because by doing this:
for(let ele in data){
consolelog(ele)
}
You're looping the properties of the array. An array is really just an object with the properties 0, 1, 2, ...
There are several ways to loop an array. In my opinion the two most common are:
// old-school...
for (let i = 0; i < data.length; i++) {
console.log(data[i]);
}
// ... new-school (ES5+)
data.forEach(ele => console.log(ele));
By your approach
let data = [
{ 'name':'suresh', 'age':25},
{ 'name':'ramesh', 'age':35},
{ 'name':'raina', 'age':15}
];
for(let ele in data){
console.log(data[ele]);
}
Try this code this work for me
for (let ele in data) {
console.log(data[ele])
}

JS loop producing no result [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Trying to create an array with a loop and then sum all the contents of the array and put the result as the contents of a DIV but when I run the fiddle I get no result and jshint says everything is well formed.
var begin = 500000;
var stop = 999999;
var arrInt = [];
// Create an array worth summing
var CreateArray = function (begin,stop) {
while(begin < stop +1){
arrInt.push(begin++);
}
};
// Sum all ints in an array
var IntSum = function (ManyInts) {
var i = arr.length; while (i--) {
return;
}
};
var example = document.getElementById("example").innerHTML;
example=IntSum(arrInt);
<div id="example"></div>
http://jsfiddle.net/7b8rqme5/
At no point do you call CreateArray. You call your other function, IntSum, which does precisely nothing. Also, you create a variable example and assign a dom element to it, then you immediately overwrite it with a (noop) function result. There are additional issues with your code as well.
My advice: slow down, determine what it is you need to accomplish, and take it step by step.
I think this is what you wanted. But not really sure what you are trying to do here.
var begin = 500000;
var stop = 999999;
var arrInt = [];
var CreateArray = function (begin,stop) {
while(begin < stop +1){
arrInt.push(begin++);
}
};
var IntSum = function (ManyInts) {
var sum = 0
var i = ManyInts.length; while (i--) {
sum += ManyInts[i];
}
return sum;
};
var example = document.getElementById("example").innerHTML;
CreateArray(begin, stop);
var saic=IntSum(arrInt);
document.getElementById("example").innerHTML = saic
http://jsfiddle.net/wpnkL6k2/

Check if an element already exist in an array in javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have the following array
array =[['apple',23,1,20],['orange',12,10,10]]
How do i check if 10 exist in the above array ?I tried to use array.indexOf but it did not work well.Can someone help ?
.indexOf() will work, the problem is with the array variable.
array variable itself contains 2 different arrays.
Try the below code.
var array = [
['apple', 23, 1, 20],
['orange', 12, 10, 10]
];
for (var i = 0; i < array.length; i++) { //Iterate through arrays in array
if (array[i].indexOf(10) > -1) {
alert("Yep");
} else {
alert("nope");
}
}
Check this JSFiddle
in ECMAScript 5 , there are two array methods some and indexOf
var search = 10 ;
var found = a.some( function( v ) {
return v.indexOf( search ) !== -1 ;
});
if ( found ) {
alert( 'exists')
}
The problem may be because:
you have nested arrays
Array.indexOf is not supported by all browsers
The following should work:
function includes(arrayOfArrays, item) {
var array, i, j;
for(i=0; i<arrayOfArrays.length; ++i) {
array = arrayOfArrays[i];
for(j=0; j<array.length; ++j) {
if(array[j] === item) {
return true;
}
}
}
return false;
}
You can use following code to search in the array.
<!DOCTYPE html>
<html>
<body>
<script>
var i,j;
var toFind = 10;
var array = new Array();
array = [['apple',23,1,20],['orange',12,10,10]]
for (i=0;i<array.length;i++)
{
for(j=0;j<array[i].length;j++)
{
if(array[i][j] == toFind)
document.write("element found <br/>");
}
}
</script>
</body>
</html>
where toFind is the element or number that you want to find.

Sum of elements, differences between code [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have two pieces of code both calculating the sum of the elements of an array:
var sum = array.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
}, 0);
or
var sum = 0;
array.forEach(function(e) {
sum += e;
});
Are there any differences between them beside different implementations? When is it better to use which one?
Besides your personal style preference, there could be also difference in actual performance. Those two look to perform similarly however.
If you're doing this operation a lot (or for large arrays) consider using the third way:
var sum = 0;
for (l = array.length; l--; ) { sum += array[l]; }
This will be way faster. Check this performance test for actual results.
Note: you will gain some speed if you cache array length. So instead of doing this:
for (var i = 0; i < array.length; i++) {...}
Do this:
var l = array.length;
for (; l--; ) { ... }
or this:
for (l = array.length; l--;) { ... }
First one is slightly heavier than the second one.
The fastest way is to avoid calling functions for each step and use loops like for.
var sum = 0;
for(var i=0, len=array.length; i<len; i++){
sum += array[i];
}
as using both of these function involves executing the callback function for each element that would incur the function calling overhead (so both re not efficent), using loop will give better performance.

access arrays of arrays or objects [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I would like to have an array of arrays like the following function shows.
function getarrayinfo(index)
{
var myarray1=new Array();
myarray[0]=[1,1.1,1.2];
myarray[1]=[0.1,0.2,0.3];
var myarray2=new Array();
for (myarray2[i])
{
myarray2[i]=myarray[i];
i++;
}
so I can do something like...
{
var arrayinfo=myarray2[marray1[index]];
return arrayinfo;
}
but this type of code does not seem to run..
Why will it run where there are Syntax errors in your code...
for (myarray2[i])
This is not how a for loop is written. Also you seem to access the index with i which is never initialized.
ALso
var myarray1=new Array();
myarray[0]=[1,1.1,1.2];
Created an myarray1 and trying to insert into myarray
Better to initialize an array with [] instead
Try this
for (var i=0; i< myarray1.length; i++) {
myarray2[i]=myarray[i];
}
Code
var myarray1 = []; // Use this to create an array
myarray1.push([1, 1.1, 1.2]); // Use push to instert instead of an index
myarray1.push([0.1, 0.2, 0.3]);
var myarray2 = [];
for (var i = 0; i < myarray1.length; i++) {
myarray2.push(myarray1[i]);
}
console.log(myarray2);
Check Fiddle
Step 1:Understand what is Multidimensional array (in your language--arrays of arrays)
var arr = [1, 2, [3, 4], 5];
alert (arr[2][1]); //alerts "4"
Step 2:this is what you want:
var container_array=[[a,b,c],[d,e,f]];
Step 3:Solution
var container_array=new Array();
sub_array_1=[1,1.1,1.2];
sub_array_2=[0.1,0.2,0.3];
container_array.push([1, 1.1, 1.2]);
container_array.push([0.1, 0.2, 0.3]);
console.log(container_array)
Example-->push in javascript
If you have many subarrays,then go for the loops

Categories