I have an array like var arr = { 30,80,20,100 };
And now i want to iterate the above array and add the iterated individual values to one function return statement for example
function iterate()
{
return "Hours" + arr[i];
}
I had tried in the following approach
function m()
{
for(var i in arr)
{
s = arr[i];
}
document.write(s);
}
The above code will gives only one value i.e. last value in an array. But i want to iterate all values like
30---for first Iteration
80---for second Iteraton
Any help will be appreciated
Iterate over using the length property rather than a for ... in statement and write the array value from inside the loop.
for (var ii = 0, len = arr.length; ii < len; ii++) {
document.write(arr[ii]);
}
That's because your write statement is outside the loop. Don't you want it like this?
function m(arr) {
for (var i = 0; i < arr.length; i++) {
s = arr[i];
document.write(s);
}
}
Also, don't use in because it will give you ALL the properties of array. Use array.length
Related
I am a totally new to coding and I'm practicing loops and arrays. I created an array with multiple sub arrays that contain pairs of strings. I'm trying to pull out and isolate each string using a nested for loops.
Here is my code:
const pairs = [['Blue', 'Green'],['Red', 'Orange'],['Pink', 'Purple']];
//attempting to use nested arrays to get each string from an array
function getString(arr){
//this loop should grab each array in the list of arrays
for (let i = 0; i < arr.length; i++){
console.log(i , arr[i]);
//this should assign each sub array to a new var to be iterated over
subArr = arr[i];
} for (let j = 0; j < subArr.length; j++){
console.log(j, arr[j]);
}
};
console.log(getString(pairs));
the problem is the output is of the last for loop is : ['Pink', 'Purple'] not each color extracted from the nested loops.
What am I doing wrong here?
Mirii
You should nest the for loops like this:
for (let i = 0; i < arr.length; i++) {
console.log(i, arr[i]);
//this should assign each sub array to a new var to be iterated over
subArr = arr[i];
for (let j = 0; j < subArr.length; j++) {
console.log(j, arr[j]);
}
}
How you have it, they'd run one after the other.
The solution is provided
:
function getString(arr) {
let arrResult = [];
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
arrResult.push(arr[i][j]);
}
}
return arrResult;
}
You need to nest the loops, just like you are nesting the arrays. Also, unless you want to alter i or j, I suggest you use .forEach as it is more simple to work with.
Example:
pairs.forEach((pair, i) => {
pair.forEach((subPair, j) => {
console.log(j, subPair);
});
});
You may also make a variable, push to it within the pair.forEach function, and return it at the end of your root function.
I hope this answers your question, thank you for posting, and have a nice day. ;P
Your loops aren't actually nested: you close the first loop before starting the second one. Because subArr is a global varialbe (no let, const, or var keyword), it's still defined in the second loop, but that's not an ideal way to do things. You also need to log arr[i][j] rather than what you have.
This fixes those issues:
function getString(arr) {
//this loop should grab each array in the list of arrays
for (let i = 0; i < arr.length; i++){
//this should assign each sub array to a new var to be iterated over
let subArr = arr[i];
for (let j = 0; j < subArr.length; j++){
console.log(arr[i][j]);
}
}
};
getString(pairs);
Another issue you have is that you're calling console.log(getString(pairs)), but getString doesn't return anything, it's logging itself. If you want it to return, for example, a newline-delimited string of all the items, you could push items to an array and return them joined with a newline (or whatever character you want):
function getString(arr) {
let ret = []
//this loop should grab each array in the list of arrays
for (let i = 0; i < arr.length; i++){
//this should assign each sub array to a new var to be iterated over
let subArr = arr[i];
for (let j = 0; j < subArr.length; j++){
ret.push(arr[i][j]);
}
}
return ret.join('\n')
};
console.log(getString(pairs));
Nested loops themselves aren't ideal, since they're not as readable as using array methods. Using forEach takes much less code:
function getString (arr) {
arr.forEach(function (subArr) {
console.log(subArr[0])
console.log(subArr[1])
})
}
getString(pairs)
Or, more succinctly, you can use map:
function getString (arr) {
return arr.map(([ a, b ]) => `${a}\n${b}`).join('\n');
}
console.log(getString(pairs))
Even more succinctly, you can do this with [].flat():
const getString = (xs = []) => xs.flat().join('\n')
console.log(getString(pairs))
I am trying to create a function that sum all numbers in an array! I am new to JavaScript and in need of someone pointing me in the right direction!
function sum(arr) {
var i = 0;
for (var index = 0; index < arr.length; index++) {
return index += arr[i];
}
}
sum([1, 2, 3]); //6
Lots of basic issues with the code.
You need a separate variable to accumulate the result in. Your code is writing into the index variable of a for loop. This is wrong for a number of reasons.
You also return after the first iteration of the loop.
Assuming you want to use a for loop (which is not the least amount of code),
function sum(arr) {
var sum = 0;
for (var index = 0; index < arr.length; index++) {
sum += arr[index];
}
return sum;
}
Use Array.reduce() for that:
function getSum(ary){
return ary.reduce(function(sum, value) {
return sum + value;
}, 0);
}
console.log(getSum([0, 1, 2, 3]));
to illustrate where your code is wrong
function sum(arr) {
var i = 0;
for (var index = 0; index < arr.length; index++) {
return index += arr[i]; // this will return from your function in the first iteration
}
}
as the comment says, return will exit your function in the first iteration
also, you're adding to index, which is supposed to be the index into the array, you want to add to i, and then return i after the loop
so, the code should be
function sum(arr) {
var i = 0;
for (var index = 0; index < arr.length; index++) {
i += arr[index];
}
return i;
}
As another answer pointed out, a probably better alternative is to use array reduce function - however the code in that answer is not the "best" usage of reduce
function getSum(ary){
return ary.reduce(function(sum, value) {
return sum + value;
}, 0);
}
can actually be written
function getSum(ary){
return ary.reduce(function(sum, value) {
return sum + value;
});
}
This uses one less iteration, because there is no "initial value", and the first iteration adds index 0 and 1 together
Sure, it's not going to make a performance difference, but why not use built-in functions properly :p
function Sum(arr) {
var sum = 0;
for (var index = 0; index < arr.length; index++) {
sum += arr[index];
}
return index;
}
Sum([1, 2, 3]); //6
Return immediately exits a function. Your code will never sum values. What is 'i' in your code!?! And what index do!?
Here's how you get your function to work:
function sum(arr) {
// this is the variable we're going to add our numbers onto
var acc = 0;
for (var index = 0; index < arr.length; index++) {
// don't return here, return is used to return from a function
acc += arr[index];
}
// after adding all numbers, return the sum
return acc
}
sum([1, 2, 3]); //6
But there are built in ways to do this, like Array.reduce() like Scott Marcus mentioned.
I've been trying the Number.isInteger() method on chrome console.
and after doing a for loop and checking the result with the console.log(arr); I'm getting an array with only one value of 1. like this [1];
var arr = [1,2,3,'some','string'];
for (var i = 0; i < arr.length; i++) {
if (Number.isInteger(arr[i])) {
arr.splice(arr.indexOf(arr[i], 1));
}
}
Any one have an idea, if I'm doing it wrong or something. thanks for help.
You have a major problem, you are continually removing items from the array while looping through it. You have to go back one step (i--) every time an item is removed.
var arr = [1,2,3,'some','string'];
for (var i = 0; i < arr.length; i++) {
if (!isNaN(arr[i])) { // isNaN return true if it's not a valid number, so we have to inverse the test
arr.splice(i, 1); // if it's a valid number remove the element at the index i (no need to search for the index using indexOf, we already have it its i)
i--; // if we remove an element, we have to go back one step (or we will leave one item behind every time we remove another)
}
}
console.log(arr);
You could use typeof instead:
var arr = [1,2,3,'some','string'];
for (var i = 0; i < arr.length; i++) {
if (typeof arr[i] == 'number') {
arr.splice(arr.indexOf(arr[i], 1));
}
}
The `.splice()' method makes changes to the array itself.
So for each iteration of the array, you are changing it fundamentally.
If you want the array to include only integers:
var arr = [1,2,3,'some','string'];
var newArray = [];
arr.forEach(function(element) {
if (Number.isInteger(element)){
newArray.push(element);
}
});
console.log(newArray);
Maybe that is not my evening :/ Very simple thing, I want to give an array as parameter to a function as arguments array:
function add() {
var sum = 0;
for (var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
The following works:
console.log(add(1,2,3,4,5,6));
But if I fill an array and give it as parameter, like:
var myNumbers = [];
for (var i=0; i<100; i++){
myNumbers.push(i);
}
console.log(add(myNumbers));
I get trouble. I think, I miss something important about the arguments array.
How should I change the add function, so that both possibilities can work with it?
This solution works for both situation :
function add() {
var arr= Array.prototype.slice.call(arguments);
arr = [].concat.apply([], arr);
var sum = 0;
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
Also simple solution for sum :
function add() {
var arr= Array.prototype.slice.call(arguments);
arr = [].concat.apply([], arr);
return arr.reduce(function(f, s){return f + s;}, 0);
}
The arguments object is an array-like object, but it is not an array. It is used to represent all arguments passed into the function. You have only passed in one value into the function, so your array is actually at index 0 of the arguments object.
However, there really isn't much point using arguments here unless you need to dynamically handle things without defining an explicit API. Just declare your parameter in the add function.
function add(arr) {
var sum = 0;
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
If you want to support both cases, as per your comment, you can do something like:
function add() {
var arr = [].concat.apply([], arguments);
var sum = 0;
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
Explanation of
[].concat.apply([], arguments)
[]. is shorthand for Array.prototype because it's an empty array.
concat merges two or more arrays together, or an array and values to go into the array.
arguments is not an array, but many of the prototype functions will work on it, due to some array-like characteristics of the object - indexed items and the length property.
apply calls a function with a given context (the this binding) and any number of arguments. In this case we still want to use the array as this value to be able to call concat, followed by all the arguments we passed into add. The result is simply all arguments as a proper array.
Here:
add(1,2,3,4,5,6);
...you're calling add with a series of discrete (separate) arguments, and each of them shows up in the arguments pseudo-array, 1 at arguments[0], 2 at arguments[1], etc.
But here:
add(myNumbers);
...you're calling add with one argument, which is an array. That's at arguments[0].
You'll want to write add to fit how you want to call it. If you want to call it with discrete arguments, write it the way you have. If you want to write it to accept an array, have it take a single argument and loop through that (which will be the array):
function add(args) {
// ^------------- the one argument
var sum = 0;
for (var i = 0; i < args.length; i++) {
sum += args[i];
}
return sum;
}
If you want to handle both, you could use Array.isArray (newish, but shimmable) to check the first argument to see if it's an array and either use it if it is or use arguments if it isn't:
function add(args) {
if (!Array.isArray(args)) {
args = arguments;
}
var sum = 0;
for (var i = 0; i < args.length; i++) {
sum += args[i];
}
return sum;
}
Side note: arguments isn't an array, it's just array-like.
You can use apply
add.apply(null, [1,2,3])
In my TypeScript project, I want to compare the values in an Array with the next value. If I am doing this in JavaScript I would do something like this:
//JS
for (var i = 0; i < codeBlocks.length; i++) {
var j = i + 1;
if (codeBlocks[i] > codeBlocks[j]) {return true;}
return false;
}
However, I really like the Typescript for of syntax as it is much more readable.
//TS
for (let codeBlock of codeBlocks) {
//logic
}
Is there a way of describing the "next iteration" value in the typescript for...of loop?
You can use entries()
for (var [index, codeBlock] of codeBlocks.entries())
{
// your code you can use index
}
DEMO
Example snippet:
var test = ['a','b','c']
for (var [index, cur] of test.entries())
{
var j = index + 1;
console.log("Current value: "+cur+" Next value: "+test[j])
}
If you want the index of an element , use the foreach function:
codeBlocks.forEach((item, index) => {
console.log(item); // item in the array
console.log(index); // item index in the array
});
You can use same syntax for (var i = 0; i < codeBlocks.length; i++) in TypeScript. But your cycle will run only once.
No. That's not the purpose of for .. of. You can read more about it on MDN.
You must use the for (var i = 0; i < codeBlocks.length; i++) syntax for that.
first Your javascript code is wrong, the last element will compare with undefined
maybe you should give a look to reduce function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
Here is a generator which generates pairs of elements:
function *pairs(array) {
let prev = array.shift();
for (v of array) {
yield [prev, v];
prev = v;
}
}
for (let pair of pairs([1,2,3])) { console.log(pair); }
If you want to also generate a last pair with the last value and undefined, then just add a yield [prev, undefined]; at the end of the function.