Reverse function in JavaScript [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to get the reverse of this array, in this case ([4,3,2,1]). The problem is I can use no reverse or other shorcuts.
const ar = [1, 2, 3, 4]
const reverse = function (arr) {
let x = arr;
for(i=0; i<x.length;i++) {
x[x.length-i-1]=x[i];
}
return x;
};
const reversedArray = reverse(ar);
console.log(reversedArray);
I thought it must be working, however when I run I get [ 1, 2, 2, 1 ]
as an output. Which is because when i=1 at the second index there is no longer 3. What can I do?

It's like swapping two variables without using a temp variable
const ar = [1, 2, 3, 4]
const reverse = function (arr) {
let x = arr, len = x.length-1;
for(i=0; i<x.length/2;i++) {
x[i]+=x[len-i];
x[len-i]=x[i]-x[len-i];
x[i]-=x[len-i]
}
return x;
};
const reversedArray = reverse(ar);
console.log(reversedArray);

Here is a simple example. But you can achieve the same result with other methods.
function reverse(array){
var new_array = [];
for(var i = 0; i< array.length; i++){
new_array[i] = array[array.length -i - 1];
}
return new_array;
}
//how to use
reverse([1,2,3,4,5]); //output

You can keep it simple by using a regular for loop, and then just unshifting the values onto a new array:
function reverse(arr) {
let reversed = [];
for (let i = 0; i < arr.length; i++) {
reversed.unshift(arr[i]);
}
return reversed;
}
console.log(reverse([1, 2, 3, 4]));
console.log(reverse([6, 7, 8, 9]));

With a while loop and starting from the end of the array :
var arr = [1, 2, 3, 4];
function arrReverse(arr) {
var res = [];
var max = arr.length - 1;
while (max > -1) {
res.push(arr[max]);
max -= 1;
}
return res;
}
var res = arrReverse(arr);
console.log(res);

You're changing the array while you do that because of Javascript's references.
You can use array.prototype.reverse (which is used as [].reverse())
Or you should set a new array and return it.

Don't use the array as a constant. It is probably not letting you make changes in the array.
Then use the reverse method:
ar.reverse();

Related

how to add 3 different number to the i, i+1 and i+2 of my array

I want to know how can I add 3 different number to the 3n, 3n+1 and 3n+2 indices. I mean for example I have following array :
var arr = [1,1,1,2,2,2,3,3,3]
and then I want add the (3n)th to 5 and then I want add (3n+1)th of an array to 2 and (3n+2) to 3,
I mean the final array I want to be like following result array:
var result = [6,3,4,7,4,5,8,5,6]
and I try to do it as following code:
// arr = [1,1,1,2,2,2,3,3,3]
let res = [];
for (let i = 0; i < arr.length; i++) {
res.push([arr[i*3] * 5,
arr[(i*3)+1] *2,
arr[(i*3)+2] *3])
}
This should do the trick:
var arr = [1,1,1,2,2,2,3,3,3],
add = [5,2,3], res=[];
// result = [6,3,4,7,4,5,8,5,6]
for (let i=0;i<arr.length;i+=add.length) add.forEach((v,j)=>res[i+j]=arr[i+j]+v);
console.log(JSON.stringify(res))
An alternative and even shorter solution (similar to #Robin's answer) would be:
var arr = [1,1,1,2,2,2,3,3,3],
add = [5,2,3], res=[];
res=arr.map((v,i)=>v+add[i%add.length]);
console.log(JSON.stringify(res))
( I noticed #Nina came up with a very similar answer ...)
You can simply use map, making use of the fact that its function argument takes the current index an optional second argument:
var arr = [1,1,1,2,2,2,3,3,3];
var result = arr.map((num, idx) => {
switch (idx % 3) {
case 0:
return num + 5;
case 1:
return num + 2;
case 2:
return num + 3;
}
});
console.log(result);
You could mapp the array directly by taking a closure over an index for the values array for adding.
var array = [1, 1, 1, 2, 2, 2, 3, 3, 3],
add = [5, 2, 3],
result = array.map((i => v => v + add[i++ % add.length])(0));
console.log(...result);

Insert odd position elements from another array elements [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have an array which looks like this [1,0,3,0,5,0] what I want is that I want to insert the zero elements the elements of this array [2,4,6] so the complete array should look like this [1,2,3,4,5,6].
let a = [1,0,3,0,5,0]
let b = [2,4,6]
// expected output [1,2,3,4,5,6]
You can also use forEach in this case for a mutating solution:
let a = [1, 0, 3, 0, 5, 0, 7, 0];
let b = [2, 4, 6, 8]
a.forEach((i, j) => {
if (i === 0)
a[j] = b[~~(j / 2)] // integer division
})
console.log(a)
You could take a variable for the index for finding falsy values and insert the replacement value at this index.
let data = [1, 0, 3, 0, 5, 0],
replacements = [2, 4, 6],
i = 0;
for (const value of replacements) {
while (data[i]) i++;
data[i] = value;
}
console.log(data);
For getting a new array, you could map the data array with the replacements.
let data = [1, 0, 3, 0, 5, 0],
replacements = [2, 4, 6],
result = data.map(v => v || replacements.shift());
console.log(result);
Below approach with work:
x = [1,0,3,0,5,0]
y = [2,4,6]
j = 0;
for(i = 0; i < x.length; i ++) {
if(x[i] === 0 && j < y.length)
x[i] = y[j++];
}
console.log(x);
You can do something like this:
const a = [1,0,3,0,5,0];
const b = [2,4,6];
let lastIndex = 0;
for (let i = 0; i < b.length; i++) {
lastIndex = a.indexOf(0, lastIndex);
a[lastIndex] = b[i];
}
console.log(a);

How to change all but one value in an array? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Suppose I have an array called array
var array = [0, 1, 2, 3, 4];
Now if I want to change a value in array I could do something like
array[0] = 'zero';
But how do I change 'every' value in array EXCEPT for a particular one?
Basically I am looking for a shorthand for this
array[0] = 9;
array[1] = 9;
array[2] = 9;
//array[3] left untouched
array[4] = 9;
Something like
array[all except 4] = 9;
How can this be easily done with javascript?
You can use .map, testing whether the index is 4, and returning either the value at that index, or your chosen new value:
const array = [
0,
1,
2,
3,
4
];
const array2 = array.map((val, i) => i === 3 ? val : 9);
console.log(array2);
If you need to mutate the original array (which usually isn't a great idea), .map won't work because it creates a new array, but you can forEach and reassign:
const array = [
0,
1,
2,
3,
4
];
array.forEach((val, i) => {
if (i !== 3) array[i] = 9;
});
console.log(array);
You can use map() to transform the array:
var array = [0,1,2,3,4];
array = array.map((el, i) => {
if(i != 3) el = 9;
return el;
});
console.log(array);
You can modify the existing array using .forEach() with an if condition inside:
let array = [0, 1, 2, 3, 4],
indexToSkip = 3;
array.forEach((_, i) => {
if(i !== indexToSkip)
array[i] = 9;
});
console.log(array);
you could do a for loop as follows:
for(i=0; i<array.length; i++){
if(i!='insert number in array you dont want to chage'){
some code..
}
}
Using a simple for loop,
var array = [0, 1, 2, 3, 4];
console.log(array)
var ignore = 3;
var replace = 5;
for (var i = 0; i < array.length; i++) {
if (i !== ignore) {
array[i] = replace;
}
}
console.log(array)
You could use Array#fill and save the value ath the given index and restore this value.
This approach mutates the given array, as wanted.
const fill = (array, all, save) => (value => (array.fill(all)[save] = value, array))(array[save]);
var array = [0, 1, 2, 3, 4];
console.log(array);
fill(array, 9, 3);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to compare one array with another in javascript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have two arrays as below:
var arr1 = [1,2,3,8,7,5,7,2,9,0];
var arr2 = [8,7,5];
I want to compare arr2 with arr1, when it will find arr2 exactly in the same sequence as it is then it should return true. i.e. if [8,7,5] is found exactly same sequence in arr1 then it will return true.
Note:
We have to do this without using indexOf.
You could use a combination of Array#some and Array#every.
var array1 = [1, 2, 3, 8, 7, 5, 7, 2, 9, 0],
array2 = [8, 7, 5],
result = array1.some(function (a, i, aa) {
return array2.every(function (b, j) {
return aa[i + j] === b;
});
});
console.log(result);
You can loop through the largest array. On each iteration, compare the next values to all of the values found in the smaller array. If they all match, then it contains the smaller array.
var arr1 = [1,2,3,8,7,5,7,2,9,0];
var arr2 = [8,7,5];
console.log(doesArrayContain(arr2, arr1));
function doesArrayContain(smallestArray, biggestArray) {
for (var i = 0; i < biggestArray.length; i++) {
var doesMatch = true;
for (var j = 0; j < smallestArray.length; j++) {
if (biggestArray[i + j] !== smallestArray[j]) {
doesMatch = false; break;
}
}
if (doesMatch) {
return true;
}
}
return false;
}

How to 'double' numbers in an array, and save it in a new array

This is a 2 step problem:
1.) I am trying to 'double' the contents of one array (original Array), save it in a new array (Doubled Array).
2.) Then assign those two arrays to an Object with 2 attributes.
New Object
Orginal Numbers
Doubled Numbers
This is what I have so far, what am I doing wrong?
var numbers = [8, 12, 5, 2, 5, 7];
var doubledNumbers = [];
function doubled(arr){
for (var i = 0; i < arr.length; i ++){
var dub = arr[i];
var dubb = dub*2;
doubledNumbers.push(dubb);
}
}
var collectionNumbers = {
orginialNumbers: numbers,
doubledNumbers: doubled(numbers)
};
console.log(collectionNumbers);
The best way to do this in Javascript is using the map function:
var doubledNumbers = numbers.map(n => n*2);
The argument to map is the function that it uses to transform the elements in the first array into the elements in the second array. It is a tremendously useful method.
To answer your original question, the reason you were seeing undefined in collectionNumbers is because you forgot to return doubledNumbers in your function (and functions by default return undefined.
var numbers = [8, 12, 5, 2, 5, 7];
var doubledNumbers = [];
function doubled(arr){
var doubledNumbers = [];
for (var i = 0; i < arr.length; i ++){
var dub = arr[i];
var dubb = dub*2;
doubledNumbers.push(dubb);
}
return doubledNumbers;
}
var collectionNumbers = {
orginialNumbers: numbers,
doubledNumbers: doubled(numbers)
};
console.log(collectionNumbers);
What's wrong with your current code, is that your doubled function is returning nothing (which means it's returning undefined).
A better function would look like this:
function doubled (arr) {
var doubled = [];
for (var i = 0; i < arr.length; i++) {
doubled.push(arr[i] * 2);
}
return doubled;
}
However, an even better solution would be to just do this:
var collectionNumbers = {
orginialNumbers: numbers,
doubledNumbers: numbers.map(function (n) { return n * 2; })
};
.map is awesome.
Your whole routine can be simplified to
var numbers = [8, 12, 5, 2, 5, 7];
var collectionNumbers = {
orginialNumbers: numbers,
doubledNumbers: numbers.map(function(n) { return n*2; })
};
console.log(collectionNumbers);
using Array.map to create a new array with the doubled numbers
using Array.from, you can double and return new array
let inputArray = [9,8,7,3,2]
let outputArray = Array.from(inputArray, x => x *2) // creates new array
console.log(outputArray)

Categories