Side effect/ changing global varaibles that pass into a function - javascript

Forgive me if this question has been asked, but I can't seem to find it.
I am attempting to create an array and reverse it (without using reverse)
This bit of code works perfect:
function reverseArrayInPlace(array) {
for (var i = 0; i < Math.floor(array.length / 2); i++) {
var old = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = old;
}
return array;
}
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
// → [5, 4, 3, 2, 1]
As you can see, it takes an in an array, does some logic, and returns the same altered array.
Although, it doesn't make sense to me why this code doesn't work:
var some_array = [6,7,8,9,10];
function reverseArrayInPlace(array) {
var replacement_array = [];
for (var i = 0; i < some_array.length; i++)
replacement_array.unshift(array[i])
array = replacement_array;
return array;
}
reverseArrayInPlace(some_array);
console.log(some_array);
// → [ 6, 7, 8, 9, 10 ]
This code also takes in an array, does some logic (and assignment) and returns an array back. Why doesn't it alter the global variable like the first one? Is there any way to change it so that it can?

Ok,you need this:
function reverseArrayInPlace(array) {
replacement_array = [];
for (var i = 0; i <array.length; i++)
{
replacement_array.unshift(array[i])
}
for(var i = 0; i <array.length; i++){
array[i]=replacement_array[i]
}
return array;
}
some_array = [6,7,8,9,10];
reverseArrayInPlace(some_array)
console.log(some_array)
Replace the variable's content will work.

Stepping through the code:
function reverseArrayInPlace(array) {
var replacement_array = [];
for (var i = 0; i < some_array.length; i++)
replacement_array.unshift(array[i])
At this point you have created a new array that's the reverse of the original array.
array = replacement_array;
Assigning a new value to array will not alter the original array; only mutable array methods or element dereferencing can effect that.
return array;
}
You're returning the new array here, so you can perform an assignment outside of the function:
some_array = reverseArrayInPlace(some_array);
console.log(some_array);
However, that no longer qualifies as modifying an array in-place; you can use unshift() and splice() though:
for (var i = 1, n = array.length; i < n; ++i) {
array.unshift(array.splice(i, 1)[0]);
}

To affect the global directly:
var some_array = [6,7,8,9,10];
function reverseArrayInPlace(array) {
var replacement_array = [];
for (var i = 0; i < array.length; i++)
replacement_array.unshift(array[i]);
for (var i = 0; i < array.length; i++)
array[i] = replacement_array[i];
}
reverseArrayInPlace(some_array);
alert(some_array);
You don't need to return array.

Related

How to get index of array elements by looping through

I'm trying to get indices of array elements. I'm going to use it for Leetcode question "Create Target Array in the Given Order".
Right now I wrote the following code but it doesn't work. (returns undefined)
var createTargetArray = function(nums) {
for(var i=0; i<nums.length; i++) {
console.log(nums.indexOf[i])
}
};
const num = [1,2,3,4,0,108];
createTargetArray(num);
Expected output from that code: [0, 1, 2, 3, 4, 5]
Am I using indexOf method incorrectly?
To get the index of the numbers, you have to call indexOf as a function call (indexOf(i))and not an array accessor (indexOf[i])
Try running the snippet below to check.
var createTargetArray = function(nums) {
for(var i=0; i<nums.length; i++) {
console.log(nums.indexOf(i))
}
};
const num = [1,2,3,4,0,108];
createTargetArray(num);
And if you want the index of exery number, that's just your variable i. You don't need to call the indexOf method.
var createTargetArray = function(nums) {
for(var i=0; i<nums.length; i++) {
console.log(i)
}
};
const num = [1,2,3,4,0,108];
createTargetArray(num);
var createTargetArray = function(nums) {
for(var i=0; i<nums.length; i++) {
console.log(nums.indexOf[i]) // <--mistake
}
};
indexOf is a method
console.log(nums.indexOf(nums[i]));
But since you are looping through the array sequentially output will always be [0, 1, 2, ... n]

Can't get i from for ((i = 0; i < koniec.length; i++) to index thru console.log(silnia(5)[i]);

In my JS script, I am trying to index thru silnia() a function that returns an array, I can do that manually without a problem: silnia(5)[1] but when I try to use an i from a for-loop it does not work.
koniec = [1,2,3];
for (i = 0; i < koniec.length; i++){
// Returns only undefined:
console.log(silnia(5)[i]);
// Works no problem:
// console.log(silnia(5)[2]);
}
function silnia(n){
var wynikSilni = [];
for(i = 1; i < (n + 1); i++){
wynikSilni.push(i);
}
return wynikSilni;
}
You're not using a var, let or const statement to declare i, so it is considered a global variable.
Which means the same i you use in the silnia function is the same i being used in the for loop outside of it; essentially, the loop outside of it runs once, the silnia increments i to 6, and once it returns to the for loop in global scope, it stops because i>koniec.length (ETA: It then tries to access sylnia(5)[6] because i equals 6 at that point in time, which is undefined)
Try this:
function silnia(n) {
var wynikSilni = [];
for (var i = 1; i < (n + 1); i++) {
wynikSilni.push(i);
}
return wynikSilni;
}
koniec = [1, 2, 3];
for (var i = 0; i < koniec.length; i++) {
// Returns only undefined:
console.log(silnia(5)[i]);
// Works no problem:
// console.log(silnia(5)[2]);
}
It's 2019 and Arrays have quite a few helpful methods that eliminate the need to set up and manage loop counters, which as others have pointed out, is the source of your problem.
Array.forEach() is the simplest of these and will help to greatly simplify your issue:
koniec = [1,2,3];
// Loop over the knoiec array
// .forEach requires a callback function to execute
// upon each loop iteration. That function will automatically
// be passed 3 arguments: the array item, the item index, the array
koniec.forEach(function(item, index){
console.log(silnia(5)[index]);
});
function silnia(n){
var wynikSilni = [];
for(i = 1; i < (n + 1); i++){
wynikSilni.push(i);
}
return wynikSilni;
}
You need to declare the variables, otherwise you use global variables for all functions.
function silnia(n) {
var wynikSilni = [];
for (var i = 1; i < (n + 1); i++) { // use var or let
wynikSilni.push(i);
}
return wynikSilni;
}
var koniec = [1, 2, 3];
for (var i = 0; i < koniec.length; i++) { // use var or let
console.log(silnia(5)[i]);
}

Replicate array to certain length in javascript

I have this array [1,2,3]
I would like to be able to set its length to 7
and have this [1,2,3,1,2,3,1] as a result.
Anyone?
const arr = [1,2,3];
// Something like
arr.resize(7);
console.log(arr); // [1,2,3,1,2,3,1]
EDIT:
Based on chevybow answer below i wrote this functions to serve my needs.
// Immutable
Array.prototype.resize = function(size) {
const array = Array(size);
for(let i = 0; i < size; i++) {
array[i] = this[i%this.length];
}
return array;
}
// Mutable
Array.prototype.resize = function(size) {
const array = this.slice(0);
this.length = size;
for(let i = 0; i < size; i++) {
this[i] = array[i%array.length];
}
}
Are those ok? or you think that putting it on the chain is not a good idea, if so why?
You can use modular arithmetic to loop through up to the length of your final array and then use the index to basically loop through and push that onto a new array
Using the current array value % array.length will get you the current position of the array by progressing it in a circular motion
let num = 7;
let array = [1,2,3];
let result = [];
for(let i = 0; i < num; i++){
result.push(array[i%array.length]);
}
console.log(result)
A simple while loop would suffice:
function repeat(arr, toLength) {
let output = [...arr];
while (output.length < toLength) output = [...output, ...arr];
return output.slice(0, toLength);
}
console.log(repeat([1, 2, 3], 7));
console.log(repeat([1, 2, 3], 2));
How about this version:
const nums = [1, 2, 3];
function resize(arr, length) {
let position = 0;
return Array.from(Array(length)).reduce((acc, _, i) => {
return acc.concat(arr[i % arr.length]);
}, []);
}
console.log(resize(nums, 7));

Reversing certain number of elements in an array javascript

I am working on a code where I need to reverse certain no of elements in an array and rest should remain same. For example is an array has values of 1,2,3,4,5,6 and I have to reverse 4 elements of it then output should be 4,3,2,1,5,6. I am using below code to achieve this but getting error, please suggest.
function reverseArray(n, a) {
var interimArray1 = [];
//var interimArray2=[];
//var finalArray=[];
for (var i < n; i >= 0; i--) {
interimArray1.push[a[i]];
}
for (var i = n; i < a.length; i++) {
interimArray1.push[a[i]];
}
for (var i = 0; i < interimArray1.length; i++) {
console.log(interimArray1[i]);
}
}
var arr = [1, 2, 3, 4, 5, 6];
var num = 4;
reverseArray(num, arr);
The error in your code is that you intend to call the push method on a[i] like so:
interimArray1.push(a[i]);
but instead you write:
interimArray1.push[a[i]];
You make that mistake twice. To give arguments to the push method, you must use round parenthesis ().
With that fixed, you will see that your code works perfectly.
You can use Array#slice, Array#splice as follow.
function partialReverse(arr, num, from = 0) {
var slicedArr = arr.slice(from, num + from);
arr.splice(from, num); // Remove `num` items from array
arr.splice(from, 0, ...slicedArr.reverse()); // Add `num` reversed items
return arr;
}
var arr = [1, 2, 3, 4, 5, 6];
console.log(partialReverse(arr, 4, 0)); // Reverse four items from `arr` starting from 0th index
console.log(partialReverse(arr, 4, 1)); // Reverse four items from `arr` starting from 1st index
Lots of hints but you seem to be missing them. ;-)
You need to assign an initial value to i, so:
for (var i = n; ... )
===========^
Also, you need to use () to call functions, not [], so:
interimArray1.push(a[i]);
==================^====^
Same in the following for block. Otherwise, the code works though it's more verbose than it needs to be.
This is working :
I'm sure there are faster ways of doing it. Also, it will only work for elements at the beginning of the array but you can adjust the function for what you want to achieve.
var reverseArray = function(arr,elementsToReverse) {
var tempArrayRev = [];
var tempArray = [];
for (var i=0;i<arr.length;i++) {
if (i < elementsToReverse) {
tempArrayRev[i] = arr[i];
} else {
tempArray.push(arr[i]);
}
}
return tempArrayRev.reverse().concat(tempArray);
}
var array = [1,2,3,4,5,6];
document.getElementById('arrayOutput').innerHTML += reverseArray(array,4);
<div id="arrayOutput">Array :<br></div>
This is the answer you can test it.
function reverseArray(n, a) {
var interimArray1 = [];
for (var i = 0; i < a.length; i++) {
interimArray1.push(a[i]);
}
for (var i = num; i >=0; i--) {
interimArray1[i-1] = a[n - i];
}
for (var i = 0; i < interimArray1.length; i++) {
console.log(interimArray1[i]);
}
}
var arr = [1, 2, 3, 4, 5, 6];
var num = 4;
reverseArray(num, arr);
You could use something like this.
function reverseArray(n, arrIn) {
// Splice splits the array in 2 starting at 0 index going n long
var arrOut = arrIn.splice(0,n);
// reverse is pretty straight forward
arrOut = arrOut.reverse();
// Concat joins the two together
return arrOut.concat(arrIn);
}

Convert an array to a 2D array (Square matrix) in javascript

I have got a little function in javascript and I want to split an array A into a 2d array.
I will be used for square matrices. Obviously,I want it to be 2x2 if a square matrix of 2x2 is in the input and so on for 3x3 and. But I'm stuck after having read a first row.So my arr rows are repeated. Does anyone have any ideas about how I can get the next rows read properly.So,for instance,lets say I do have an array
A = [2,1,4,5,1,2,3,1,9]
Then I want my array arr to look like this:
arr = [[2,1,4],[5,1,2],[3,1,9]]
This will later be used for calculation a determinant of a matrix.
function create2Darray(clname) {
var A = document.getElementsByClassName(clname);
var arr = new Array();
var rows = Math.sqrt(A.length);
for (var i = 0; i < rows; i++) {
arr[i] = new Array();
for (var j = 0; j < rows; j++) {
arr[i][j] = A[j].value;
}
}
}
You are assigning always the same value. It should be something like:
arr[i][j] = A[i*rows+j].value;
EDIT: Here's a complete function without the DOM manipulation (that is, A is a simple array of integers):
function create2Darray(A) {
var arr = [];
var rows = Math.sqrt(A.length);
for (var i = 0; i < rows; i++) {
arr[i] = [];
for (var j = 0; j < rows; j++) {
arr[i][j] = A[i * rows + j];
}
}
return arr;
}
console.log(create2Darray([1, 2, 3, 4, 5, 6, 7, 8, 9]))

Categories