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 am adding all categories after ticking them to true if they exists in selected categories of result but it combines previous categories results with current one. I tried closure but it doesn't give me fresh object. Check out fiddle.
var allCatsResult = [{"id":1},{"id":2}, {"id":3}, ... ];
var catsArray = [1, 2] // Array of ids from allCatsResult
var result = [
{"id":1, selectedCategories:[{"id":1},{"id":2}]},
{"id":2, selectedCategories:[{"id":4},{"id":5}]},
...
];
for (var i = 0; i < results.length; i++) {
var tmp = allCatsResult; // tried to add function form here didn't work
for (var k = 0; k < results[i].selectedCategories.length; k++) {
var index = catsArray.indexOf(results[i].selectedCategories[k].category_id);
if(index !== -1) {
tmp[index].ticked = true;
}
}
results[i].categories = tmp;
}
Above code gives combined result for ticked = true for all categories in each result.
You need to copy/clone the array of objects, or you're manipulating the original. There are a few ways apparently. I chose the following:
var tmp = JSON.parse(JSON.stringify(allCatsResult));
This will create a new array of objects in tmp, and it will correctly only modify the clone.
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);
There might be a very simple solution my problem but just not being able to find one so please help me to get to my solution in the simplest way...
The issue here is that I have data being displayed in a tabular form. Each row has 5 columns and in one of the columns it shows multiple values and so that's why I need to refer to a value by something like this row[1]['value1'], row[1]['value2'] & then row[2]['value1'], row[2]['value2'].
I declare the array
var parray = [[],[]];
I want to store the values in a loop something like this
for(counter = 0; counter < 10; counter ++){
parray[counter]['id'] += 1;
parray[counter]['isavailable'] += 0;
}
Later I want to loop through this and get the results:
for (var idx = 0; idx < parray.length; idx++) {
var pt = {};
pt.id = parray[schctr][idx].id;
pt.isavailable = parray[schctr][idx].isavailable;
}
Obviously iit's not working because Counter is a numeric key and 'id' is a string key ..my question how do I achieve this ??
Thanks for all the answers in advance.
JS has no concept of "associative arrays". You have arrays and objects (map). Arrays are objects though, and you can put keys, but it's not advisable.
You can start off with a blank array
var parray = [];
And "push" objects into it
for(counter = 0; counter < 10; counter++){
parray.push({
id : 1,
isAvailable : 0
});
}
Then you can read from them
for (var idx = 0; idx < parray.length; idx++) {
// Store the current item in a variable
var pt = parray[idx];
console.log(pt);
// read just the id
console.log(parray[idx].id);
}
Like I did here
What you want inside your array is just a plain object:
// just a regular array
var parray = [];
for(var counter = 0; counter < 10; counter++){
// create an object to store the values
var obj = {};
obj.id = counter;
obj.isavailable = 0;
// add the object to the array
parray.push(obj);
}
later:
for (var idx = 0; idx < parray.length; idx++) {
var pt = parray[idx];
// do something with pt
}
I am trying to convert Java code to Javascript and I am trying to assign data to 3 dimensional array and I am getting "TypeError: can't convert undefined to object " error. Following is my code. Thanks in advance for any help.
var initData = [[2], [12], [2]];
for (var i = 0; i < 12; i++)
{
initData[0][i][0] = -1;
initData[0][i][1] = -1;
initData[1][i][0] = -1;
initData[1][i][1] = -1;
}
[[2], [12], [2]];
That's not a declaration of dimensions, that's four array literals. There are no multidimensional arrays in JS. They're just one-dimensional lists that can contain arbitrary values (including other lists).
To create and fill an array that contains other arrays you have to use the following:
var initData = []; // an empty array
for (var i = 0; i < 2; i++) {
initData[i] = []; // that is filled with arrays
for (var j = 0; j < 12; j++) {
initData[i][j] = []; // which are filled with arrays
for (var k = 0; k < 2; k++) {
initData[i][j][k] = -1; // which are filled with numbers
}
}
}
or, to apply your loop unrolling:
var initData = [[], []]; // an array consisting of two arrays
for (var i = 0; i < 12; i++) {
// which each are filled with arrays that consist of two numbers
initData[0][i] = [-1, -1];
initData[1][i] = [-1, -1];
}
initData is a list of three lists, [2], [12] and [2]. Each one with one element.
In order to init a list(or array), you must do
var initData = [];
Then store in initData another list, like initData[0] = [] and so on... like it's mentioned, arrays/lists in javascript aren't initialized with a limit size.