Wondering why i needed to add 4 to the array length in order for it to print out the entire array in reverse?
before i added 4 it was just using the .length property and it was only printing out 6543.
thanks in advance!
function reverseArray(array) {
var newArray =[];
for(var i = 0; i <= array.length+4; i++) {
newArray += array.pop(i);
}
return newArray;
}
var numbers = [1,2,3,4,5,6];
console.log(reverseArray(numbers));
array.pop removes (and returns) the last element. This affects the length of the array. The length is checked on every iteration, so since the array is getting shorter every time, the loop is ended early.
You can create a loop and pop items until it is empty, but another thing to take into account, is that it is the original array you are altering. I think a function like reverseArray shouldn't alter the array numbers that was passed to it if it returns another one. So a better solution would be a simple loop that iterates over all items without modifying the array.
function reverseArray(array)
{
var newArray =[];
for (var i = array.length-1; i >= 0; i--) {
newArray.push(array[i]);
}
return newArray;
}
var numbers = [1,2,3,4,5,6];
console.log(reverseArray(numbers));
console.log(numbers); // Should be unaltered.
If you don't mind modifying the array, you can use the reverse() method of the array:
var numbers = [1,2,3,4,5,6];
numbers.reverse();
console.log(numbers);
In Javascript, pop always removes the last element of the array. This shortens length, meaning that i and array.length were converging.
You can do a few things to avoid this behavior:
Store the original length when you start the loop: for (var i = 0 , l = array.length; i < l; i++)
Copy over values without modifying the original array
When you pop the items from the array, the item is removed from the array. As you increase the counter and decrease the length, they will meet halfway, so you get only half of the items.
Use push to put the items in the result. If you use += it will produce a string instead of an array.
If you use pop, then you can just loop while there are any items left in the array:
function reverseArray(array) {
var newArray = [];
while (array.length > 0) {
newArray.push(array.pop());
}
return newArray;
}
You can leave the original array unchanged by looping through it backwards and add items to the new array:
function reverseArray(array) {
var newArray = [];
for (var i = array.length - 1; i >= 0; i--) {
newArray.push(array[i]);
}
return newArray;
}
use following method for same output
function reverseArray(array)
{
var newArray =[];
var j = array.length-1;
for(var i = 0; i < array.length; i++)
{
newArray[j]= array[i]; j--;
}
return newArray;
}
var numbers = [1,2,3,4,5,6];
console.log(reverseArray(numbers));
Related
I need to create function that creates and returns array. Its size needs to match the rows parameter, and each next element contains consecutive integers starting at 1. To call this function I need to use argument 5. Here below is what I wrote so far. Can you tell me what's wrong here?
function createArray(rows) {
for(let i = 1; i < rows.length; i++) {
console.log(rows[i]);
}return rows;
}
createArray(5);
You need to create an array and return it, whereas you return just rows which is a number. The idea of using a for loop is the best way to go. In that loop you just need to set the values in the array accordinlgy.
Another problem in your code is that rows is of type number and does have a property length but that does not have the desired value. So we just use rows in the for loop. We start the loop with i = 0 because array indices start at 0.
Code
function createArray(rows) {
let arr = new Array(rows);
for (let i = 0; i < rows; i++) {
arr[i] = i + 1;
}
return arr;
}
console.log(createArray(5));
We can not use length property for number. create an empty array and then push values into that array until required size is achieved.
function createArray(rows) {
var arr = [];
for(let i = 1; i <= rows; i++) {
arr.push(i);
}return arr;
}
createArray(5);
I think what you want is createArray(5) return [1,2,3,4,5] if that's the case you could do this
function createArray(rows) {
const arr = []
for(let i = 1; i <= rows; i++) {
arr.push(i);
}
return arr;
}
console.log(createArray(5));
The problem is, that rows.length is not available on 5, because 5 is a number.
You have to use an array as parameter:
Array(5) creates an array with the length of 5 and fill("hello") fills this array with "hello" values.
function createArray(rows) {
for (let i = 1; i < rows.length; i++) {
console.log(rows[i]);
}
return rows;
}
const rows = Array(5).fill("hello");
createArray(rows);
I don't know, if this is the behaviour you want, if not, I misunderstood your question.
I try to return a multidimensional array into a function to iterate it but I'm not sure what's wrong with my logic
const arr = [[1,2], [3,4],[5,6]]
for(let i = 0; i < thirdInterval.length-1; i++){
getNumbers(thirdInterval[i], thirdInterval[i+1])
}
The result that I want to achieve is return the first element into the first argument of the function and the second element of the array into the second argument of the function.
What you are doing here is looping through the array and getting only the array at the index i, e.g arr[0] which is [1,2]. and (thirdInterval[i], thirdInterval[i+1]) is actually equals to ([1,2], [3,4])
to access the first and second elements you should address them like the following:
for(let i = 0; i < thirdInterval.length-1; i++){
getNumbers(thirdInterval[i][0], thirdInterval[i][1])
}
const arr = [[1,2][3,4][5,6]];
for (var i = 0; i < arr.length; i++;) {
func(arr[i][0], arr[i][1];
}
You are iterating an array with sub-arrays, which means that thirdInterval[i] contains two items. You can get the items using the indexes thirdInterval[i][0] and thirdInterval[i][1], but since you're calling a function with those values, you can use spread instead - getNumbers(...thirdInterval[i]).
In addition, the loop's condition should be i < thirdInterval.length if you don't want to skip the last item.
Demo:
const thirdInterval = [[1,2],[3,4],[5,6]]
const getNumbers = console.log // mock getNumbers
for (let i = 0; i < thirdInterval.length; i++) {
getNumbers(...thirdInterval[i])
}
Why won't this function reverseArrayInPlace work? I want to do simply what the function says - reverse the order of elements so that the results end up in the same array arr. I am choosing to do this by using two arrays in the function. So far it just returns the elements back in order...
var arr = ["a","b","c","d","e","f"]
var arr2 = []
var reverseArrayInPlace = function(array){
var arrLength = array.length
for (i = 0; i < arrLength; i++) {
arr2.push(array.pop())
array.push(arr2.shift())
}
}
reverseArrayInPlace(arr)
Here's a simpler way of reversing an array, using an in-place algorithm
function reverse (array) {
var i = 0,
n = array.length,
middle = Math.floor(n / 2),
temp = null;
for (; i < middle; i += 1) {
temp = array[i];
array[i] = array[n - 1 - i];
array[n - 1 - i] = temp;
}
}
You "split" the array in half. Well, not really, you just iterate over the first half. Then, you find the index which is symmetric to the current index relative to the middle, using the formula n - 1 - i, where i is the current index. Then you swap the elements using a temp variable.
The formula is correct, because it will swap:
0 <-> n - 1
1 <-> n - 2
and so on. If the number of elements is odd, the middle position will not be affected.
pop() will remove the last element of the array, and push() will append an item to the end of the array. So you're repeatedly popping and pushing just the last element of the array.
Rather than using push, you can use splice, which lets you insert an item at a specific position in an array:
var reverseArrayInPlace = function (array) {
var arrLength = array.length;
for (i = 0; i < arrLength; i++) {
array.splice(i, 0, array.pop());
}
}
(Note that you don't need the intermediate array to do this. Using an intermediate array isn't actually an in-place reverse. Just pop and insert at the current index.)
Also, interesting comment -- you can skip the last iteration since the first element will always end up in the last position after length - 1 iterations. So you can iterate up to arrLength - 1 times safely.
I'd also like to add that Javascript has a built in reverse() method on arrays. So ["a", "b", "c"].reverse() will yield ["c", "b", "a"].
A truly in-place algorithm will perform a swap up to the middle of the array with the corresponding element on the other side:
var reverseArrayInPlace = function (array) {
var arrLength = array.length;
for (var i = 0; i < arrLength/2; i++) {
var temp = array[i];
array[i] = array[arrLength - 1 - i];
array[arrLength - 1 - i] = temp;
}
}
If you are doing Eloquent Javascript, the exercise clearly states to not use a new array for temporary value storage. The clues in the back of the book present the structure of the solution, which are like Stefan Baiu's answer.
My answer posted here uses less lines than Stefan's since I think it's redundant to store values like array.length in variables inside a function. It also makes it easier to read for us beginners.
function reverseArrayInPlace(array) {
for (var z = 0; z < Math.floor(array.length / 2); z++) {
var temp = array[z];
array[z] = array[array.length-1-z];
array[array.length-1-z] = temp;
}
return array;
}
You are calling the function with arr as parameter, so both arr and array refer to the same array inside the function. That means that the code does the same as:
var arr = ["a","b","c","d","e","f"]
var arr2 = []
var arrLength = arr.length;
for (i = 0; i < arrLength; i++) {
arr2.push(arr.pop())
arr.push(arr2.shift())
}
The first statements get the last item from arr and places it last in arr2. Now you have:
arr = ["a","b","c","d","e"]
arr2 = ["f"]
The second statement gets the first (and only) item from arr2 and puts it last in arr:
arr = ["a","b","c","d","e","f"]
arr2 = []
Now you are back where you started, and the same thing happens for all iterations in the loop. The end result is that nothing has changed.
To use pop and push to place the items reversed in the other array, you can simply move the items until the array is empty:
while (arr.length > 0) {
arr2.push(arr.pop());
}
If you want to move them back (instead of just using the new array), you use shift to get items from the beginning of arr2 and push to put them at the end of arr:
while (arr2.length > 0) {
arr.push(arr2.shift());
}
Doing a reversal in place is not normally done using stack/queue operations, you just swap the items from the beginning with the items from the end. This is a lot faster, and you don't need another array as a buffer:
for (var i = 0, j = arr.length - 1; i < j; i++, j--) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
This swaps the pairs like this:
["a","b","c","d","e"]
| | | |
| +-------+ |
+---------------+
I think you want a simple way to reverse an array. Hope it will help you
var yourArray = ["first", "second", "third", "...", "etc"]
var reverseArray = yourArray.slice().reverse()
console.log(reverseArray)
You will get
["etc", "...", "third", "second", "first"]
With the constraints I had for this assignment, this is the way I figured out how to solve the problem:
var arr = ["a","b","c","d","e","f"]
var arr2 = []
var reverseArrayInPlace = function(array){
var arrLength = array.length
for (i = 0; i < arrLength; i++) {
arr2.push(array.pop())
}
for (i = 0; i < arrLength; i++) {
array[i] = arr2.shift()
}
}
reverseArrayInPlace(arr)
Thank you for all your help!
***** edit ******
For all of you still interested, I rewrote it using some help from this thread and from my own mental devices... which are limited at this point. Here is it:
arr = [1,2,3,4,5,6,7,8,9,10,11,12,13]
arr2 = ["a","b","c","d","e","f"]
arr3 = [1,2,3]
arr4 = [1,2,3,4]
arr5 = [1,2,3,4,5]
var reverseArrayInPlace2 = function(array) {
var arrLength = array.length
var n = arrLength - 1
var i = 0
var middleTop = Math.ceil(arrLength/2)
var middleBottom = Math.floor(arrLength/2)
while (i < Math.floor(arrLength/2)) {
array[-1] = array[i]
array[i] = array[n]
array[n] = array[-1]
// console.log(array)
i++
n--
}
return array
}
console.log(reverseArrayInPlace2(arr))
console.log(reverseArrayInPlace2(arr2))
console.log(reverseArrayInPlace2(arr3))
console.log(reverseArrayInPlace2(arr4))
console.log(reverseArrayInPlace2(arr5))
P.S. what is wrong with changing global variables? What would the alternative be?
Here is my solution with no temp array. Nothing groundbreaking, just shorter version of some proposed solutions.
let array = [1, 2, 3, 4, 5];
for(let i = 0; i<Math.floor((array.length)/2); i++){
var pointer = array[i];
array[i] = array[ (array.length-1) - i];
array[(array.length-1) - i] = pointer;
}
console.log(array);
//[ 5, 4, 3, 2, 1 ]
I know this is a old question, but I came up with an answer I do not see above. It is similar to the approved answer above, but I use array destructuring instead of a temporary variable to swap the elements in the array.
const reverseArrayInPlace = array => {
for (let i = 0; i < array.length / 2; i++) {
[array[i], array[array.length - 1 - i]] = [array[array.length - 1 - i], array[i]]
}
return array
}
const myArray = [1,2,3,4,5,6,7,8,9];
console.log(reverseArrayInPlace(myArray))
This solution uses a shorthand for the while
var arr = ["a","b","c","d","e","f"]
const reverseInPlace = (array) => {
let end = array.length;
while(end--)
array.unshift(array.pop());
return array;
}
reverseInPlace(arr)
function reverseArrayInPlace (arr) {
var tempArr = [];
for (var i = 0; i < arr.length; i++) {
// Temporarily store last element of original array
var holdingPot = arr.pop();
// Add last element into tempArr from the back
tempArr.push(holdingPot);
// Add back value popped off from the front
// to keep the same arr.length
// which ensures we loop thru original arr length
arr.unshift(holdingPot);
}
// Assign arr with tempArr value which is the reversed
// array of the original array
arr = tempArr;
return arr;
}
I want to display an array without showing of indexes. The for loop returns the array indexes which is not showing in usual declaration.
I want to send an array like [1,2,3 ...] but after retrieving from for loop, I haven't the above format. How can I store my values as above.
var a = [];
for (var i = 1; i < 8; i++) {
a[i] = i;
};
console.log(a);
Outputs:
[1: 1, 2: 2 ...]
Desired output:
[1,2,3]// same as console.log([1,2,3])
Array indices start at zero, your loop starts at 1, with index 0 missing you have a sparse array that's why you get that output, you can use push to add values to an array without using the index.
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
console.log(a);
The problem is that you start your array with 1 index, making initial 0 position being empty (so called "hole" in array). Basically you treat array as normal object (which you can do of course but it defeats the purpose of array structure) - and because of this browser console.log decides to shows you keys, as it thinks that you want to see object keys as well as its values.
You need to push values to array:
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
I have to disagree with the answers provided here. The best way to do something like this is:
var a = new Array(7);
for (var i = 0; i < a.length; i++) {
a[i] = i + 1;
}
console.log(a);
Your code is making each index equal to i, so use it this way
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
console.log(a);
I have a comma separated string, out of which I need to create a new string which contains a random order of the items in the original string, while making sure there are no recurrences.
For example:
Running 1,2,3,1,3 will give 2,3,1 and another time 3,1,2, and so on.
I have a code which picks a random item in the original string, and then iterates over the new string to see if it does not exist already. If it does not exist - the item is inserted.
However, I have a feeling this can be improved (in C# I would have used a hashtable, instead of iterating every time on the new array). One improvement can be removing the item we inserted from the original array, in order to prevent cases where the random number will give us the same result, for example.
I'd be happy if you could suggest improvements to the code below.
originalArray = originalList.split(',');
for (var j = 0; j < originalArray.length; j++) {
var iPlaceInOriginalArray = Math.round(Math.random() * (originalArray.length - 1));
var bAlreadyExists = false;
for (var i = 0; i < newArray.length; i++) {
if (newArray[i].toString() == originalArray[iPlaceInOriginalArray].toString()) {
bAlreadyExists = true;
break;
}
}
if (!bAlreadyExists)
newArray.push(originalArray[iPlaceInOriginalArray]);
}
Thanks!
You can still use a 'hash' in javascript to remove duplicates. Only in JS they're called objects:
function removeDuplicates(arr) {
var hash = {};
for (var i=0,l=arr.length;i<l;i++) {
hash[arr[i]] = 1;
}
// now extract hash keys... ahem...
// I mean object members:
arr = [];
for (var n in hash) {
arr.push(n);
}
return arr;
}
Oh, and the select random from an array thing. If it's ok to destroy the original array (which in your case it is) then use splice:
function randInt (n) {return Math.floor(Math.random()*n)}
function shuffle (arr) {
var out = [];
while (arr.length) {
out.push(
arr.splice(
randInt(arr.length),1 ));
}
return out;
}
// So:
newArray = shuffle(
removeDuplicates(
string.split(',') ));
// If you sort the first array, it is quicker to skip duplicates, and you can splice each unique item into its random position as you build the new array.
var s= 'Function,String,Object,String,Array,Date,Error,String,String,'+
'Math,Number,RegExp,Group,Collection,Timelog,Color,String';
var A1= s.split(',').sort(), A2= [], tem;
while(A1.length){
tem= A1.shift();
while(A1[0]== tem) tem= A1.shift();
if(tem) A2.splice(Math.floor(Math.random()*A2.length), 0, tem);
}
alert(A2.join(', '))
With your solution, you are not guaranteed not to pick same number several times, thus leaving some others of them never being picked. If the number of elements is not big (up to 100), deleting items from the source array will give the best result.
Edit
originalArray = originalList.split(',');
for (var j = 0; j < originalArray.length; j++) {
var iPlaceInOriginalArray = Math.round(Math.random() * (originalArray.length - 1 - j));
var bAlreadyExists = false;
for (var i = 0; i < newArray.length; i++) {
if (newArray[i].toString() == originalArray[iPlaceInOriginalArray].toString()) {
bAlreadyExists = true;
break;
}
}
var tmp = originalArray[originalArray.length - 1 - j];
originalArray[originalArray.Length - 1 - j] = originalArray[iPlaceInOriginalArray];
originalArray[iPlaceInOriginalArray] = tmp;
if (!bAlreadyExists)
newArray.push(originalArray[iPlaceInOriginalArray]);
}