JS cannot call function on array items - javascript

I created a function to check an array if the element of the array is divisible by the next item. If not is shall remove the next item from the array.
I created a test array consisting of two arrays. When I loop over them and console.log them they get returned as expected.
When I call my function (deleteItem) in the for loop instead of the console.log it just returns the result of the first array element and not the second. I am really confused and do not understand this. Can anyone please give me a hint what I am doing wrong?
Thank you in advance!
let testArray = [[240,12, 10, 8,23],[240,12, 10, 8,24]];
function deleteItem(array) {
if(array.length<=1){
return array;
}
else{
for(i=0; i<array.length-1;i++) {
let changed = true;
while(changed){
if(array[i]%array[i+1]!=0) {
array.splice(i+1,1);
i=0;
break;
}
else {changed=false};
}
}
}
return array;
}
If I only console log it returns both elements as expected:
for(i=0;i<testArray.length;i++){
console.log( testArray[i]);
//console.log(deleteItem( testArray[i]));
}
returns:
[240, 12, 10, 8, 23]
[240, 12, 10, 8, 24]
If I use my function it only calls the first array element
for(i=0;i<testArray.length;i++){
console.log( testArray[i]);
console.log(deleteItem( testArray[i]));
}
returns:
[240, 12, 10, 8, 23]
[240, 12]
I expect:
[240, 12, 10, 8, 23]
[240, 12]
[240, 12, 10, 8, 24]
[240, 12]

Don't forget to declare your for-loop variable with a "let".
It works fine as soon as you add the let. (Same inside the deleteItem function)
for(let i = 0; i < testArray.length; i++){
console.log(testArray[i]);
console.log(deleteItem(testArray[i]));
}
There is no problem when you just loop through your testArray and output every element but inside your deleteItem() function, you have another for-loop with a variable named "i" that is not declared locally.
That means:
You start the testArray loop with a global i = 0. Then you call the deleteItem function that also uses the same global i for its for-loop. So after the deleteItem function is done, the global i is set to 4 and the original for-loop condition doesn't hold anymore. That's why the deleteItem function is not called for your second testArray element.

Related

iterate through array in javascript and return in new array

i'm totally new to coding: i want to iterate through the array input, select the positive numbers only, then put them in a new array liste and then print the new array in the console. what am i doing wrong here?!?
let input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15];
var liste = [];
function cut(input){
for (var i=0; i<cut.length; i++){
if (i>0){
liste.push(input[i]);
return liste;
}
}
var result = cut(input);
console.log(result);
Since I can't accurately portray in a comment what I would want to explain, I am posting an answer:
I find it much easier to balance braces when I format my code like so
function cut(input)
{
for (var i=0; i<cut.length; i++)
{
if (i>0)
{
liste.push(input[i]);
return liste;
}
}
And now its pretty apparent where the unbalanced brace is.
There are other syntax errors that others have already been pointed out:
Its not cut.length, rather input.length.
Your if statement needs to be if (input[i] > 0), not if (i > 0)
return liste shouldn't be inside of the loop, rather at the end of the function, because once a value is found it will stop the loop and immediately return only 1 value inside of the array.
Here should be a working example of what you intended to do. Other than those few syntax errors, good job with the logic!
let input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15];
function cut(input){
let liste = [];
for (var i=0; i<input.length; i++){
if (input[i]>0){
liste.push(input[i]);
}
}
return liste;
}
var result = cut(input);
console.log(result);
I'll attempt to combine the points made in several other answers here, and add some more explanation.
Fixing the For Loop, One Line at a Time
Most of your code is fine; the only issues are in your for loop. Let's review that from top to bottom.
for (var i=0; i<cut.length; i++){
You have the right idea here. However, in this for loop, you want to make i loop from 0 to the length of the array you're looping over-- not the length of the function you wrote. So you should replace cut.length with input.length. This way, i will loop from 0 to 14.
if (i>0){
i is a number you're using to keep track of how far into the array you are. As mentioned above, for your array, it will go from 0 to 14. You're trying to check if the number at the ith position is positive, not if i itself is. To access the number at the ith position, you can use input[i] instead of just i.
liste.push(input[i]);
This line is fine; nice work! You're finding the number at the ith position of the input array and adding it to liste. Because of the if statement before, this only happens when that number is positive.
return liste;
This line will return the list immediately, exiting your cut function. You want this to happen only after you're done looping through all the numbers, so you just need to move this line after the for loop.
And one last thing-- you forgot a curly brace to end your if statement. Be careful with this, as it can mess up your program.
I've gone ahead and made all these changes. You can check them out in the following snippet:
let input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15];
var liste = [];
function cut(input){
for (var i=0; i<input.length; i++){
if (input[i]>0){
liste.push(input[i]);
}
}
return liste;
}
var result = cut(input);
console.log(result);
Some things to explore:
What happens if you move var liste = []; inside cut, like in Shmack's answer? Does the code still work? Why?
What happens if you rename all inputs inside cut to something else? Does the code still work? Why?
Understanding these questions isn't necessary, but learning the answers may help you to get better at coding for the future.
A Better Method
But wait, there's more! What if there was a built-in feature that could do this more easily for us?
Introducing filter!
filter is a useful method that all arrays have that lets them filter their contents based on a function that you give them. Using filter lets you bypass writing a for loop at all (although it is still good to practice writing them; sometimes they are very useful).
The function you provide to filter is usually written as an "arrow function", which basically just means turning this:
function(input){
//Do stuff
return output;
}
into this:
(input) => {
//Do stuff
return output;
}
It's very useful for writing quick little functions, so I'll use it in my example.
To filter the array using filter and arrow functions, all you have to do is this:
let input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15];
var result = input.filter((number)=>{return number > 0});
console.log(result);
There are 4 mistakes in your code
i<cut.length, you have to check the input length not the length of the function
i>0 , it should be input[i]>0 , since you are comparing the input indecis
Curly braces of if statement is not closed
Return is not outside the for loop
After fixing all these it should work
let input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15];
var liste = [];
function cut(input){
for (var i=0; i<input.length; i++){ //error 1
if (input[i]>0){//2
liste.push(input[i]);
}//error 3
}
return liste;//error 4
}
var result = cut(input);
console.log(result);
for (var i=0; i<input.length; i++){
here you want to user input.length not cut.length, because you want i to go through all the indexes in the input array.
You also forgot a brace to close the for loop
In addition you are returning from inside the loop, which means the loop is exited, so as soon as the first element is found, you will exit the function, so you'll only get one element in your liste.
Questions like these can be solved with googling a bit but for now, it seems like in your second expression, you have i<cut.length which doesn't make sense. You have to change it to i < input.length because you want to iterate through the input. You also can't have a return statement because you will exit out of the loop. You can also use a higher order function like the filter function to return any number that is higher than 0. input.filter((num) => num > 0) Hope this helped!!

JavaScript: filter() Method Returning Back Original Array and Not Filtering

I have the following code below using the filter() array function.
arr = [12, 5, 8, 130, 44]
function test(arr) {
return arr.filter((element) => {
return element >= 10
});
}
console.log(test(arr))
My code is returning the original array ([ 12, 5, 8, 130, 44 ]) and not filtering at all. What am I doing wrong?
Note: I want to use the filter() method for this.
Filter returns a new array, so depending on how you are using your function, you most likely are looking at the original array, which you cannot do, you need to look at the filtered results.
let arr = [12, 5, 8, 130, 44]
function test(arr) {
return arr.filter((element) => {
return element >= 10
});
}
// The filtered results
console.log('The filtered array', test(arr))
// The original array
console.log('The original array', arr)
To modify the array in place you can use a while loop, and then splice the elements like this which will modify the array in place.
let arr = [12, 5, 8, 130, 44]
// Get the initial length of the array
let i = arr.length
// Loop backwards over the array as not to skip values when they get removed
while(--i) {
if(arr[i] > 10) continue
arr.splice(i, 1)
}
console.log(arr)
Instead of a while, you could also just assign the value back to the original array overwriting is original value.
let arr = [12, 5, 8, 130, 44]
function test(arr) {
return arr.filter((element) => {
return element >= 10
});
}
// Assign the result back to arr
arr = test(arr)
// The new value of arr
console.log(arr)
You code is missing a few things, but you are on the right track. Array.filter doesn't change the original array. Set a variable,var filter, and set it equal to the function test. Then console.log(filter(arr))

2 Different Outputs When Reversing Array

I am learning Javascript on a book and have to practice reversing an array by creating my own reverse function. The array must be reversed without creating a new variable to hold the reversed array. I thought I found a solution, but when I try to output my answer in 2 different ways (see below), I get different outputs:
function reverseArrayInPlace(array) {
for (var i = 0; i < array.length; i += 1) {
array = array.slice(0, i).concat(array.pop()).concat(array.slice(i));
}
console.log(array);
}
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
Here are the outputs:
reverseArrayInPlace(array);
console.log(array);
> [ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ]
> [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
When console.log() is used within the function, I get my desired answer.
When console.log() is used outside the function, I get the original array with the last element missing. I would like an explanation to this phenomenon.
The array in the function is on a different scope than that at the global / window level -- the global array is never touched; the function changes a local copy of it instead.
If you didn't pass array as a parameter to the function, then it would act on the now unmasked global array variable:
function reverseArrayInPlace() { // <-- no parameter
for (var i = 0; i < array.length; i += 1) {
array = array.slice(0, i).concat(array.pop()).concat(array.slice(i));
}
console.log(array);
}
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
reverseArrayInPlace();
console.log(array);
(...although it is generally bad practice to use globals like that, partly because it's easy to accidentally mask them with local variables just as you did here. A better pattern would be for functions to receive their data as params and return a value, so you can decide, when you call the function, what to assign that returned value to.)
Inside reverseArrayInPlace you are reassigning the array variable, not changing (mutating) it. The array you pass in, therefore, is not changed. The inside console.log sees the new array while the one outside sees the original.
Perhaps you want something like this instead
function reverseArrayInPlace(array) {
for (var i = 0; i < array.length; i += 1) {
array = array.slice(0, i).concat(array.pop()).concat(array.slice(i));
}
return array;
}
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var newArray = reverseArrayInPlace(array)
console.log(newArray)
Just a different approach by using the function stack for storing an item of the array by popping the value, check the length of the array and call the function again with the same object reference and then unshift the temporary stored value.
While working for a small amount of values and because of the limited stack, it is not advisable to use this beside of educational purpose.
function reverseArrayInPlace(array) {
var temp = array.pop();
if (array.length) {
reverseArrayInPlace(array);
}
array.unshift(temp);
}
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
reverseArrayInPlace(array);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
In the first loop of your for you are calling array.pop() which modifies the array passed as argument, but then you are creating a new array storing it in the same variable, so the reference to the original array is lost, and then in the subsequent loops the modified array is the one being generated inside your function.
Look at this code, I added a line to copy the original array, thus not modificating the original passed as argument.
function reverseArrayInPlace(array) {
array = array.slice(); //copying the passed array to not change the original
for (var i = 0; i < array.length; i += 1) {
array = array.slice(0, i).concat(array.pop()).concat(array.slice(i));
}
console.log(array);
}
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
reverseArrayInPlace(array);
console.log(array);

Stand in Line Freecodecamp

Im currently working thru the exercises on the javascript portion of the freecodecamp site and Im trying to understand why a particular method worked in solving it.
function nextInLine(arr, item) {
// Your code here
arr.push(item);
var firstItem = arr.shift(arr);
return firstItem; // Change this line
}
Im trying to understand why I had to create the variable firstItem in the first place? Is there another way I could of went about solving this exercise? If so please let me know how you went about solving it.
Welcome to Stack Overflow :)
I've also gone through this task as part of undertaking the Free Code Camp front end certification. For reference, this is the task: https://www.freecodecamp.com/challenges/stand-in-line
Write a function nextInLine which takes an array (arr) and a number
(item) as arguments. Add the number to the end of the array, then
remove the first element of array. The nextInLine function should then
return the element that was removed.
While your solution delivers the desired outcome, it is possible to solve this task without declaring a variable (firstItem in your code). I've prepared and demo with description for you here: http://codepen.io/PiotrBerebecki/pen/xEYbgv
The crucial thing is to understand that:
The shift() method removes the first element from an array AND returns
that element. This method changes the length of the array.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
function nextInLine(arr, item) {
// arr is now: [5,6,7,8,9]
arr.push(item); // add 10 to the and of array
// arr is now: [5,6,7,8,9,10]
return arr.shift(); // remove first element of arr (5)
// and then return this first element (5),
// arr is now [6,7,8,9,10]
}
var testArr = [5,6,7,8,9];
console.log(nextInLine(testArr, 10)); // 5
console.log("After: " + JSON.stringify(testArr)); // After: [6,7,8,9,10]
The .shift function doesn't use any arguments. It just removes the first element of array one by one.
Here is the correct code.
function nextInLine(arr, item) {
arr.push(item);
var remove=arr.shift();
}
return arr.shift(arr);
with out declaring the variable to return
function nextInLine(arr, item){
arr.push(item); //this will add new element to the array, for our case, our array become [10, 11, 12, 13, 14, 15]
return arr.shift(arr); //the shift() method will remove the first //element and then return its value.
//for our case, our new array becomes [11, 12, 13, 14 ,15], 10 will be returned as the value of the removed element
return item; //will return the value of the item argument
};
const myArray = [10, 11, 12, 13, 14];
console.log(nextInLine(myArray, 15));
//array.push(item) in this case will add 15 to the end of the array, and the new array will now be [10, 11, 12, 13, 14, 15]
console.log(myArray);
//arr.shift(arr) will take the new array[10, 11, 12, 13, 14, 15] and remove the first element, which is "10", and then return it. Our new array will now be [11, 12, 13, 14, 15].

Copy first element in an array and replace the last

I have a javascript array with x amount of values.
How can I replace the last element in that array with the first? (Not switch positions but remove the last array and put the first in the last position)
Example:
Initial Array: [9, 14, 23 ,12 ,1]
Final Array: [9, 14, 23, 12, 9]
array[array.length-1] = array[0];
You don't need to know very much. For starters see JavaScript Array Object.
You can use any values for the array! Hope this helps! :)
// replaces the last index of an array with the first.
var replace = function(InputArray){
//saves the first index of the array in var a
var a = InputArray[0];
//removes the last index of the array
InputArray.pop;
//places a copy of the first index in the place where the last index was
InputArray.push(a);
//returns the array
return InputArray;
}
//call the function
replace([9, 14, 23 ,12 ,1]);
// result => [9, 14, 23, 12, 1, 9]
//If you want, you can log it in the console!
console.log(replace([9, 14, 23 ,12 ,1]));

Categories