This question already has answers here:
JS: Reverse an Array but Reverse the Original Array Only --> Error: running with no output
(6 answers)
Reversing an array in javascript?
(3 answers)
Reversing an array without 'reverse' or duplicating an array
(10 answers)
Closed 1 year ago.
I want to use the same variable array to output the reverse an integer array. But, I only got the first value print out. Not sure where I did wrong.
Here is my code:
let array = [3, 8, 9, 6, 4, 2]
reverseArray(array);
function reverseArray(array){
let left =0;
for(i = 0; i <= array.length - 1; i++){
let right = array.length - 1 - i;
let temp = right;
right = left;
left = temp;
array = array[left];
}
console.log(array);
}
Assuming this is a learning exercise, note that you are iterating too many times:
function reverseArray(array){
const len = array.length;
for (let i = 0; i < len/2; ++i) {
const temp = array[i];
const tail = len - i - 1;
array[i] = array[tail];
array[tail] = temp;
}
}
const array = [3, 8, 9, 6, 4, 2];
reverseArray(array);
console.log(array);
As others have pointed out, the reason for truncation is the fact that you assigned an array element to the array variable, turning it from an array into a scalar.
"In real life", you should use array.reverse().
it's because you set the array as a single value by doing array = array[left].
you just override the array variable and placing a single element inside it.
changing this line to array[right] = array[left] would be a good start.
if you want to fix it all, you need to iterate only through HALF of the array (so that you won't reverse it twice - back to normal), and make the whole swap (not just replace one element):
let array = [3, 8, 9, 6, 4, 2]
reverseArray(array);
function reverseArray(array){
for(i = 0; i < array.length / 2; i++){
let right = array.length - 1 - i;
let temp = array[right];
array[right] = array[i];
array[i] = temp;
}
console.log(array);
}
Note: if you want to reverse an array you can simply use the array prototype "reverse" function like this:
let array = [3, 8, 9, 6, 4, 2];
array = array.reverse();
console.log(array);
Actually you changing index so right use to store index not value and in the last line array = array[left] is you are trying to give value and that is array[0] = 1 so that's why 1 is coming
Right way to do this
let array = [3, 8, 9, 6, 4,2]
reverseArray(array);
function reverseArray(array){
for(i = 0; i <= (array.length - 1)/2; i++){// need to iterate only half otherwise it remain same so for exampale 0th index replace with 4th index and 4th with 0 so at last both at their same position
let right = array.length - 1 - i;
let temp = array[right];
array[right] = array[i];
array[i] = temp;
}
console.log(array);}
Just use build in NodeJs function:
array.reverse()
What you are actually doing wrong is
array = array[left]
On the right side of this equation is a value of array at a specific index while on the right side of this array is a whole array
Related
I'm learning for loops in JS and am trying to learn how to console.log the first and last element in an array on one iteration, then console.log the second and second to last elements, etc.
here's what I have tried:
for (let i=0; i<myArray.length; i++){
console.log(myArray[i]);
console.log(myArray[i-1];
}
This is printing elements from my array, but not in the correct order
So what you are trying to achieve is to print the last element, the second last element, etc...
You can use the myArray.length property to do it, just substract the iterator + 1 to the array length and obtain the result you want.
for (let i=0; i<myArray.length; i++){
console.log(myArray[i]);
console.log(myArray[myArray.length - (i + 1)]);
}
The (i + 1) is because the .length property returns the number of item of the array, but not the maximum index of the array. So if the length of the array is 5, the maximum index of the array is 4 (since index starts from 0). You can also write it like: myArray[myArray.length - i - 1]
Here an example:
const myArray = [1, 2, 3, 4, 5];
for (let i=0; i<myArray.length; i++){
console.log(myArray[i]);
console.log(myArray[myArray.length - (i + 1)]);
}
Create a temporary copy of your array, then use shift (to remove the head element) and pop (to remove the tail element) until the copy is empty:
const realArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const temporary = realArray.slice();
while (temporary.length) {
const e1 = temporary.shift();
// do something with e1
console.log(e1);
const e2 = temporary.pop();
if (e2) {
// note that e2 _might not exist_ so: always test
console.log(e2);
}
}
You can use two counters that works on opposite direction
i will move forward with increment as i++.
j will move backward with decrement as j--.
If there are even numbers of elements in an array then you should print both numbers arr[i] and arr[j]. But be sure to handle the odd number of elemetns in an array then you have to print either of arr[i] or arr[j]
function print(arr) {
let i = 0;
j = arr.length - 1;
while (i <= j) {
if (i !== j) {
console.log(arr[i], arr[j]);
} else console.log(arr[j]);
i++;
j--;
}
}
print([1, 2, 3, 4, 5, 6, 7, 8]);
print([1, 2, 3, 4, 5, 6, 7, 8, 9]);
Here's one way to do it, reverse the array and use the same index. Since array.reverse() mutates the original array, we slice() it in order to use a copy.
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
array.forEach((a, i) => {
let b = array.slice().reverse()[i]
if (i < array.length / 2) console.log(a, b)
})
let output = '';
for (let i = 0; i < (myArr.length) /2; i++){
output += myArr[i] + myArr[myArr.length-1-i];
}
console.log(output)
Just check for i === 0 to indicate the start of the loop and hence, you can print the last element of array
const myArray = ['first', 1, 2, 3, 'last'];
for (let i = 0; i < myArray.length - 1; i++) {
console.log(myArray[i]);
if (i === 0) {
console.log(myArray[myArray.length - 1]);
}
}
I am trying to write code that reverses an array in place without using the reverse function (I'm busy learning JS so just doing an exercise from Eloquent JavaScript).
function reverseArrayInPlace(arr) {
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[(arr.length - 1) - i];
}
return arr;
}
This was the code that I wrote which doesn't quite work, I know this is because I have already reassigned arr[0] and arr[1] so if I call reverseArrayInPlace([1, 2, 3, 4 ,5]), [5, 4, 3, 4, 5] is returned.
This was given as the solution:
function reverseArrayInPlace(array) {
for (let i = 0; i < Math.floor(array.length / 2); i++) {
let old = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = old;
}
return array;
}
Could anyone please explain what's happening in the solution so I can better understand? Thanks :)
So here is what is happening in this function:
for(let i = 0; i < Math.floor(array.length / 2); i++):
they are using the Math.floor() method to make sure that you only iterate through half of the array. That is why your original solution repeated elements instead of reversing them.
let old = array[i]:
This is a temporary variable to hold the element at the current index in the loop while you swap them.
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = old;
this swaps the elements.
which only leaves return array;
You only need to loop over half of the array since you are swapping items; if you loop over the entire array, you will swap each item twice, not changing the array at all. In each iteration, you just copy over the value at the reflected index, instead of transposing the two values, for which you need a temporary variable to store one of the values.
Say you have an array [1, 2, 3, 4, 5]. The code starts from left most element, and swap it with the right most element. so you get [5, 2, 3, 4, 1]. Then it does the same for the next element in the array, swap it with the second to right element, and you'll get [5, 4, 3, 2, 1]. Math.floor(array.length) make sure that the already swapped elements don't swap again, so it will only go through the first half of the array.
This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 4 years ago.
So im trying to remove the numbers 1,2,7,14 in the array but i dont know how to remove it. I did not find any solution that is similar to this
function mySelect(){
var prime1 = document.getElementById('input1').value;
var prime2 = document.getElementById('input2').value;
var n = prime1 * prime2;
console.log(n);
var foo = new Array(n);
console.log(foo.length);
var range = [];
for(var i=1;i<foo.length;i++){
range.push(i);
}
console.log(range);
// --------------------------------------------//
var half = Math.floor(n / 2), // Ensures a whole number <= num.
str = '1', // 1 will be a part of every solution.
i, j;
// Determine our increment value for the loop and starting point.
n % 2 === 0 ? (i = 2, j = 1) : (i = 3, j = 2);
for (i; i <= half; i += j) {
n % i === 0 ? str += ',' + i : false;
}
str += ',' + n; // Always include the original number.
console.log(str);
}
After you pushed the values to the array you can use a filter function, like so:
let nonos = [ 1, 2, 7, 14 ];
range = range.filter((element) => !nonos.includes(element));
This code specifies the values you want removed inside an array and then runs a loop on your original array and checks whether the element you're on is included in your nonos array and if it is, don't include it in your original array, else do.
To remove all instances of the provided numbers from an array:
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function removeNumbers(array, ...numbers) {
numbers.forEach((number) => {
var index = array.indexOf(number);
while(index >= 0) {
array.splice(index, 1);
index = array.indexOf(number);
}
});
}
removeNumbers(array, 3, 2, 5, 7);
console.log(array);
find the index first and then apply splice method.
var array=[1,2,3,4,5,6,7,8,9,10]
console.log(array)
find the index of value you want to delete
let indexa=array.indexOf(2);
apply splice method to delete 1 value from applied index
array.splice(indexa,1);
console.log(array)
This question already has answers here:
Finding out how many times an array element appears
(6 answers)
Closed 6 years ago.
just started learning JS and had a test about loops and wasn't successful in finding an answer to this:
I would like to see how many times the number 1 appears in the arrray.
All i was able to do is get a true answer when 1 appears in the array.
Been trying to figure this out since last Wednesday..
Thanks!
var v = [1, 3, 5, 4, 3, 0, 0, 1, 1];
count = 1;
for (var i = 0; i < v.length; i++){
console.log (count == v[i])
}
If you want to count the number of times a value appears in the array, you firstly need to initialise a variable outside of the loop (if you initialise in the loop, the value will be reset on each iteration of that loop).
Secondly you need a conditional statement that you will check for, in this case if a value is equal to one. As its a loop, and more then one value in the array, we can get the current index's value like v[i] (which you correctly did). Now you need to plus one to your counter, counter++ is the same as counter = counter + 1;. Now the if statement i used below has the === this is an equals operator that also check to see if the two values are of the same type.
var v = [1, 3, 5, 4, 3, 0, 0, 1, 1];
var count = 0;
for (var i = 0; i < v.length; i++){
if(v[i] === 1){
count++;
}
}
console.log (count);
You can make use of the filter method which returns the array with specified condition and then you can do a count by using the length property.
var v = [1, 3, 5, 4, 3, 0, 0, 1, 1];
console.log((v.filter(x => x === 1)).length);
Close! What you need to do is initialize a count variable and then iterate over the array. At each index, you check if the element matches the number. If it does, you increment the count
var v = [1, 3, 5, 4, 3, 0, 0, 1, 1];
var count = 0;
var number = 1;
for (var i = 0; i < v.length; i++){
if (v[i] == number) {
count++;
}
}
console.log(count);
you have to increase the count, you are only checking if the count equals what the current item is
var v = [1, 3, 5, 4, 3, 0, 0, 1, 1];
count = 0;
for (var i = 0; i < v.length; i++){
var cur = v[i]; // < gets the current item
if (cur == 1) // < If the current item is 1
count += 1; // < Then increase the count by 1
console.log (count); // < Log what the count is
}
You can do this with a variety of techniques, but in your case, you need to actually check the array value for 1 as you loop, which you aren't doing.
var v = [1, 3, 5, 4, 3, 0, 0, 1, 1];
// Don't assume that there are any occurrences of 1 in the array
count = 0;
for (var i = 0; i < v.length; i++){
// Test to see if the current array item is 1 and, if so, increment the counter
// The "long-hand" way:
//if(v[i] === 1){
// count++;
//}
// Above "if" could also be written using JavaScript's "ternary" operator as this:
count = (v[i] === 1) ? ++count : count;
}
// The report should be after the loop has completed.
console.log ("1 appears in the array " + count + " times.")
Here's another (of many) techniques, but this one removes the loop, the if test and the counter completely. It also takes arrays out of the algorithm, which, in turn, can make the code much easier to understand:
var v = [1, 3, 5, 4, 3, 0, 0, 1, 1];
// Turn array into string and (using regular expressions) remove any char that is not 1
var s = v.join("").replace(/[0, 2-9]+/g, "");
// Just check the length of the string after removing non-1 chars:
console.log ("1 appears in the array " + s.length + " times.");
I have an array of randomly generated numbers.
I want to create a function that divides all those numbers. Basically, assuming that I have 5 numbers in the array [5, 7, 6, 8, 2], I want the output to be equal to 5 / 7 / 6 /8 / 2
array = [5, 7, 6, 8, 2];
var total = 1;
for(var i = 0; i < array.length; i++) {
total = array[i] / total;
}
return total;
This is what I did so far, but the output isn't the correct one. Any idea where I am doing wrong?
You've basically got your math backwards. With your approach, you want to progressively divide total, rather than progressively dividing by total.
var total = array[0];
for (var i = 1; i < array.length; i++)
total = total / array[i];
return total;
Try this. It uses the array's reduce method along with es6 arrow functions which makes it a one liner. You can use babel to convert es6 syntax to es5.
var arr = [5, 7, 6, 8, 2];
arr.reduce((prev,curr) => prev/curr);
ES5 version:
var arr = [5, 7, 6, 8, 2];
arr.reduce(function(prev, curr) {
return prev/curr;
});
As you can see in the docs, Array.reduce() will reduce a list of values to one value, looping through the list, applying a callback function and will return a new list. In that callback you can access four parameteres:
previousValue: If you pass an argument after callback function, previousValue will assume that value, otherwise it'll be the first item in array.
currentValue: The current value in the loop.
index: Index of the current item on loop.
array: The list
Well you messed up with the total, you kept dividing each new number with the result. You just have to flip the '/' operators.
array = [5, 7, 6, 8, 2];
var total = array[0];
for(var i = 1; i < array.length; i++) {
total = total/array[i];
}
return total;
Try this ...
array = [5, 7, 6, 8, 2];
var total = array[0];
for(var i = 1; i < array.length; i++) {
total = array[i] / total;
}
return total;