What is the difference between [4,null,6] and [4,6] - javascript

Here is the question:
Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.
And here is my code:
function diffArray(arr1, arr2) {
var newArr = [];
// Same, same; but different.
for (i = 0; i < arr1.length; i++) {
for (j = 0; j < arr2.length; j++)
while (arr1[i] === arr2[j])
delete arr2[j];
newArr = arr2;
}
return newArr;
}
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));
Please, tell me my mistakes.

If you work using indices as references which you delete, you'll leave those indices undefined.
You have to use push to add an item and splice to remove one.
The time complexity of the following code should be: O(nm) where n and m are the lengths of the arr1 and arr2 arrays respectively.
function diffArray(arr1, arr2) {
var newArr = [];
for (i = 0; i < arr1.length; i++) {
for (j = 0; j < arr2.length; j++)
while (arr1[i] === arr2[j])
arr2.splice(j, 1);
newArr = arr2;
}
return newArr;
}
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));
This should work, but I've found a different way that is a bit slower for short arrays but much faster for longer array.
The time complexity of the following code should be: O(3(n + m)), which is reduced to O(n + m) where n and m are the lengths of the arr1 and arr2 arrays respectively.
Look at this fiddle.
Here's it:
function diffArray(arr1, arr2) {
let obj1 = {}, obj2 = {};
for (let l = arr1.length, i = 0; i < l; i++)
obj1[arr1[i]] = undefined;
for (let l = arr2.length, i = 0; i < l; i++)
obj2[arr2[i]] = undefined;
let a = [];
for (let arr = arr1.concat(arr2), l = arr.length, i = 0, item = arr[0]; i < l; i++, item = arr[i])
if (item in obj1 !== item in obj2)
a.push(item);
return a;
}
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));

The task you are trying to complete asks you to create a new array, but instead you modify arr2. It would probably be easiest to just copy all elements not included in the other array to a new array, like this:
function diffArray(arr1, arr2) {
var newArray = [];
arr1.forEach(function(el) {
if (!arr2.includes(el)) {
newArray.push(el);
}
});
arr2.forEach(function(el) {
if (!arr1.includes(el)) {
newArray.push(el);
}
});
return newArray;
}
If you would rather try and fix your code instead, I can try to have another look at it.

I've used Array.prototype.filter method:
function diffArray(arr1, arr2) {
var dif01 = arr1.filter(function (t) {
return arr2.indexOf(t) === -1;
});
var dif02 = arr2.filter(function (t) {
return arr1.indexOf(t) === -1;
});
return (dif01).concat(dif02);
}
alert(diffArray([1, 2, 3, 6, 5], [1, 2, 3, 4, 7, 5]));
If you still want to use your code and delete the common elements, try to use Array.prototype.splice method instead of delete: the latter deletes the value, but keeps the index empty, while Array.prototype.splice will remove those whole indices within the given range and will reindex the items next to the range.

You can use Array.prototype.filter:
var array1 = [1, 2, 3, 5];
var array2 = [1, 2, 3, 4, 5];
var filteredArray = filter(array1, array2).concat(filter(array2, array1));
function filter(arr1, arr2) {
return arr1.filter(function(el) { return arr2.indexOf(el) < 0; });
}
Here is a working JSFiddle.

Try this:
function diffArray(arr1, arr2) {
var ret = [];
function checkElem(arrFrom, arrIn) {
for (var i = 0; i < arrFrom.length; ++i) {
var elem = arrFrom[i];
if (arrIn.indexOf(elem) === -1)
ret.push(elem);
}
}
checkElem(arr1, arr2);
checkElem(arr2, arr1);
return ret;
}
I hope this can solve your problem.

Related

Array Difference, nested For Loops

function arrayDiff(a, b) {
let result = [];
for (let i = 0; i < a.length; i++) {
for (let j = 0; j < b.length; j++) {
if (a[i] !== b[j]) {
result.push(a[i]);
}
}
}
return result;
}
console.log(arrayDiff([1,2,2,3], [1])); // output: [2,2,3]
console.log(arrayDiff([1,2,2,3], [1,2])); // output: [1,2,2,3,3] // desired output: [3]
Trying to solve Array Difference, multiple items inside 'b' causing unwanted output.
Consider using a Set and Array#filter.
const
arr1 = [1, 5, 3, 7, 9],
arr2 = [5, 1, 10, 13],
s = new Set(arr2),
res = arr1.filter((a) => !s.has(a));
console.log(res);

How to find the largest group of numbers in an array and return them separately in javascript?

How can I make a function that returns only the numbers greater than the number that I entered?
My code here isn't working, and I don't know why.
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var num = Number(prompt('number'));
function findBiggestNumbers(num) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] > num) {
num = arr[i];
}
}
return num;
// }
console.log(findBiggestNumbers(num));
To work with arrays you could use the filter function, it returns a subset of the array with some condition. So, you can simpley do:
var num = 5; //using 5 as an example
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var b = a.filter(number => number > num);
You can put this into an function.
You need to create a new empty array and fill it with numbers that are bigger than input value.
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var num = Number(prompt('number'));
function FindBiggestNumbers(num) {
let biggerThanArray = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] > num) {
biggerThanArray.push(arr[i]);
}
}
return biggerThanArray;
}
console.log(FindBiggestNumbers(num));
You can start to understand and do some fun things with functional JS.
Similar to the answer from Daladier Sampaio I've used filter to return an array where each element passes a condition (el > num) in the callback function. (filter, reduce, and map were introduced in ES5 and are very useful array methods and well worth learning how to use.)
In this example, I've passed in - and called - a whole function named greaterThan instead.
greaterThan
1) Accepts an argument - n, the number from the prompt in this case
2) Returns an array - the callback function that will operate on each array element. What's interesting about this function is that it carries a copy of num with it when it returns. A function like this that retains a copy of its outer lexical environment like that is called a closure. Understanding what they are and how they work is a useful JS skill, and one that is often picked up on in JS interviews.
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const num = Number(prompt('number'));
// accepts a number and returns a callback function
// that accepts an array element and
// tests it against the value of `n`
function greaterThan(n) {
return function (el) {
return el > n;
};
}
// calling greater than with our prompted number
// returns that new callback function that checks each
// array element
const out = arr.filter(greaterThan(num));
console.log(out);
Modern JS >= ES6 will allow you to condense the amount of code you have to write using arrow functions. The following one-line code will work in place of the function in the example:
const greaterThan = n => el => el > n;
You could use Array.prototype.filter():
function FindBiggestNumbers(num) {
return arr.filter(n => n > num);
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var number = Number(prompt("Enter a number"));
console.log(FindBiggestNumbers(number));
The alternative is using a nested if statement inside a for loop like so:
First make a new array:
function FindBiggestNumbers(num) {
var newArr = [];
}
Then loop through the original array:
function FindBiggestNumbers(num) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
}
}
And if you find an element of the array greater than the number, add it to the new array:
function FindBiggestNumbers(num) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] > num) {
newArr.push(arr[i]);
}
}
}
Finally, return the new array:
function FindBiggestNumbers(num) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] > num) {
newArr.push(arr[i]);
}
}
return newArr;
}
Demonstration:
function FindBiggestNumbers(num) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] > num) {
newArr.push(arr[i]);
}
}
return newArr;
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var number = Number(prompt("Enter a number"));
console.log(FindBiggestNumbers(number));

freecodecamp Challenges- Seek and Destroy

I am trying to solve this challenge Seek and Destroy. I can't figure out what is wrong. Any help ?
Seek and Destroy
You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments.
This is the initial code below:
function destroyer(arr) {
// Remove all the values
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
This is my Code below:
function destroyer(arr) {
var letsDestroyThis = [];
var i =1 ; while (i<arguments.length) {
letsDestroyThis.push(arguments[i]);
i++;
}
for(var j=0 ; j< arguments[0].length; j++) {
for (var k= 0; k< letsDestroyThis.length; k++) {
if(arguments[0][j] === letsDestroyThis[k]){
arguments[0].splice(j, 1);
}
}
}
return arguments[0];
}
destroyer([2, 3, 2, 3], 2, 3);
Thanks in Advance!
You can create an array of all values that are supposed to be removed. Then use Array.filter to filter out these values.
Note: Array.splice will change original array.
function destroyer() {
var arr = arguments[0];
var params = [];
// Create array of all elements to be removed
for (var k = 1; k < arguments.length; k++)
params.push(arguments[k]);
// return all not matching values
return arr.filter(function(item) {
return params.indexOf(item) < 0;
});
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
function destroyer(arr) {
/* Put all arguments in an array using spread operator and remove elements
starting from 1 using slice intead of splice so as not to mutate the initial array */
const args = [...arguments].slice(1);
/* Check whether arguments include elements from an array and return all that
do not include(false) */
return arr.filter(el => !args.includes(el));
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
This worked for me:
function destroyer(arr) {
// Remove all the values
var args = Array.from(arguments);
var filter = [];
for (i = 0; i < args[0].length; i++) {
for (j = 1; j < args.length; j++) {
if (args[0][i] === args[j]) {
delete args[0][i];
}
}
}
return args[0].filter(function(x) {
return Boolean(x);
});
}
console.log(
destroyer([1, 2, 3, 1, 2, 3], 2, 3)
);
//two ways of resolving the Seek and Destroy challenge on the FreeCodeCamp
//I was trying to simplify this code, please post your solutions, simplifying the code
//as much has its possible
function destroyer1 (arr){
//get array from arguments
var args = Array.prototype.slice.call(arguments);
args.splice(0,1);
for (var i = 0; i < arr.length; i++){
for(var j = 0; j < args.length; j++){
if(arr[i]===args[j]){
delete arr[i];
}
}
}
return arr.filter(function(value){
return Boolean(value);
});
}
//--------------------------------------
function destroyer(arr) {
// Remove all the values
//Get values from arguments of the function to an array, index 0(arr[0] will be "arr",
//rest of indexes will be rest of arguments.
var args = Array.from(arguments);
for (var i = 0 ; i < args[0].length; i++){
for (var j = 1; j < args.length; j++){
if(args[0][i] === args[j]){
delete args[0][i];
}
}
}
return args[0].filter(function(value){
return Boolean(value);
});
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
console.log(destroyer1([1,6,3,9,8,1,1], 3,1));
This is my Code:
function destroyer(arr) {
var argsBeRemove = [...arguments];
argsBeRemove.shift();
return arr.filter(val => {
return argsBeRemove.indexOf(val) == -1;
});
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
Here is my version of Seek and Destroy. I assume that there are no zero elements in input (that assumption allows to pass the challenge). But that way I can make found elements equal zero and then just filter them out. It is pretty straight forward and no index mess when deleting elements in for loops.
function destroyer(arr) {
// Remove all the values
var args = Array.prototype.slice.call(arguments);
var temp = [];
temp = arguments[0].slice();
for (j = 1; j < args.length; j++) {
for (i = 0; i < arguments[0].length; i++) {
if (arguments[0][i] == arguments[j]) {
temp[i] = 0;
}
}
}
function isZero(value) {
return value !== 0;
}
var filtered = temp.filter(isZero);
return filtered;
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
function destroyer(arr) {
var args = Array.prototype.slice.call(arguments, 1);
return arr.filter(destroyNum);
function destroyNum(element) {
return !args.includes(element);
}
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
Give this a shot, it is way less convoluted:
function destroyer(arr) {
// arr1 is equal to the array inside arr
var arr1 = arr.slice(arguments);
// arr2 becomes an array with the arguments 2 & 3
var arr2 = Array.prototype.slice.call(arguments, 1);
// this function compares the two and returns an array with elements not equal to the arguments
return arr1.concat(arr2).filter(function(item) {
return !arr1.includes(item) || !arr2.includes(item)
})
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments.
The accepted solution returns a new array, instead of removing the elements from the existing array.
This can be achieved efficiently by iterating the array in reverse and removing any elements matching any of the filter arguments.
function destroy(original, ...matches) {
if('length' in original) {
let index = original.length
while(--index > -1) {
if(matches.includes(original[index])) {
original.splice(index, 1)
}
}
}
return original;
}
const original = [1, 2, 3, 1, 2, 3]
destroy(original, 2, 3)
console.log(original);
My answer is similar to previous one, but I didn't use indexOf. Instead of that I checked the values in cycle, but compiler gives me a warning to not to declare function in cycle.
function destroyer(arr) {
// Remove all the values
var temp = [];
for (var i = 1; i < arguments.length; i++) {
temp.push(arguments[i]);
arr = arguments[0].filter(function(value) {
return ( value !== temp[i - 1]) ;
});
}
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
We can get the arguments behind the array, which are the number required to be removed and store them to a list. Then, we can just use a filter to filter out the numbers that needed to be removed.
function destroyer(arr) {
let removeList=[...arguments].slice(1);
return arr.filter(e=>removeList.indexOf(e)===-1);
}
I know isn't the shortest way to do it, but i think is the more simple to understand in an intermediate level.
function destroyer(arr, ...elements) {
var i =0;
while(i<=arr.length){ //for each element into array
for(let j =0; j<elements.length; j++){ //foreach "elements"
if(arr[i]==elements[j]){ // Compare element arr==element
arr.splice(i,1); //If are equal delete from arr
i--; //Check again the same position
j=0;
break; //Stop for loop
}
}
i++;
}
return arr;
}
console.log(destroyer(["possum", "trollo", 12, "safari", "hotdog", 92, 65, "grandma", "bugati", "trojan", "yacht"], "yacht", "possum", "trollo", "safari", "hotdog", "grandma", "bugati", "trojan"));
console.log(destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3));
function destroyer(arr) {
let newArray = Array.from(arguments).splice(1)
return arr.filter(item => !(newArray.includes(item)))
}

How do I sum up 2 dimensional array, ex index 0+index0

I encountered a problem!
for example! here is my 2 dimensional array: var array=[[1,2,3,4],[2,3,4,5],[3,4,5,6]];
and my desired outcome is : [[1,2,3,4],[2,3,4,5],[3,4,5,6],[6,9,12,15]]
the [6,9,12,15] came from adding the same index numbers of the previous inner arrays. (ex 1+2+3, 2+3+4, 3+4+5, 4+5+6 more clear : index 1 + index 1+ index1 produces 9)
I am so confused so far, the closes i did was to sum up [1,2,3,4][2,3,4,5][3,4,5,6], but I cant seem to do something with each and individual numbers :(
The question requested me to do nested for loops, So i cant use any thing like reduce, map, flatten, etc...
try with this way:https://jsfiddle.net/0L0h7cat/
var array=[[1,2,3,4],[2,3,4,5],[3,4,5,6]];
var array4 = [];
for (j = 0; j < array[0].length; j++) {
var num =0;
for(i=0;i< array.length;i++){
num += array[i][j];
}
array4.push(num);
}
array.push(array4);
alert(array);
Just iterate over the outer array and the inner arrays and add the values to the result array array[3].
var array = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]];
array.forEach(function (a) {
a.forEach(function (b, i) {
array[3] = array[3] || [];
array[3][i] = (array[3][i] || 0) + b;
});
});
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');
https://jsfiddle.net/0L0h7cat/
var array = [
[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6]
];
var sumArr = [];
for (var i = 0; i < array[0].length; i++) {
sumArr[i] = 0;
for (var j = 0; j < array.length; j++)
sumArr[i] += array[j][i];
}
array.push(sumArr);
If you are interested in Arrow Functions, this will work:-
var array = [[1, 2, 3, 4],[2, 3, 4, 5],[3, 4, 5, 6]];
var count = [];
array.forEach(x => x.forEach((y, i) => count[i] = (count[i] || 0) + y));
array.push(count);
console.log(array);
NOTE: Not cross browser support yet.
This is how -
var array=[[1,2,3,4],[2,3,4,5],[3,4,5,6]];
var array2=[]
for (var i = array[0].length;i--;) {
var sum=0;
for (var j = array.length; j--;) {
sum=sum+array[j][i];
}
array2.push(sum)
}
array.push(array2.reverse());
document.write('<pre>'+JSON.stringify(array) + '</pre>');
But I'm sure there are more elegant methods. I'm just learning by answering questions myself.
A simplistic approach with just conventional for loops
var input = [[1,2,3,4],[2,3,4,5],[3,4,5,6]];
function getSumOfArrayOfArrays(inputArray) {
var length = inputArray.length;
var result = [];
for(var i=0; i<length; i++){
for(var j=0; j<=3; j++){
result[j] = result[j] ? result[j] + inputArray[i][j] : inputArray[i][j];
}
}
return result;
}
var output = getSumOfArrayOfArrays(input); // [6,9,12,15]
var desiredOutput = input;
desiredOutput.push(output)
document.write(JSON.stringify(desiredOutput));
// [[1,2,3,4],[2,3,4,5],[3,4,5,6],[6,9,12,15]]
I try to avoid writing nested for loops.
var arrayOfArrays=[
[1,2,3,4],
[2,3,4,5],
[3,4,5,6]
];
//define a function to extend the Array prototype
Array.prototype.add = function(otherArray){
var result = [];
for(var i = 0; i < this.length; i++) {
result.push( this[i] + otherArray[i] )
}
return result;
};
//reduce array of arrays to get the result array `sum`
var sum = arrayOfArrays.reduce(function(arrayA, arrayB){
//`arrayA`+`arrayB` becomes another `arrayA`
return arrayA.add(arrayB)
});
//put `sum` back to `arrayOfArrays`
arrayOfArrays.push(sum);
document.write('<pre>' + JSON.stringify(arrayOfArrays) + '</pre>');

How can I reverse an array in JavaScript without using libraries?

I am saving some data in order using arrays, and I want to add a function that the user can reverse the list. I can't think of any possible method, so if anybody knows how, please help.
Javascript has a reverse() method that you can call in an array
var a = [3,5,7,8];
a.reverse(); // 8 7 5 3
Not sure if that's what you mean by 'libraries you can't use', I'm guessing something to do with practice. If that's the case, you can implement your own version of .reverse()
function reverseArr(input) {
var ret = new Array;
for(var i = input.length-1; i >= 0; i--) {
ret.push(input[i]);
}
return ret;
}
var a = [3,5,7,8]
var b = reverseArr(a);
Do note that the built-in .reverse() method operates on the original array, thus you don't need to reassign a.
Array.prototype.reverse() is all you need to do this work. See compatibility table.
var myArray = [20, 40, 80, 100];
var revMyArr = [].concat(myArray).reverse();
console.log(revMyArr);
// [100, 80, 40, 20]
Heres a functional way to do it.
const array = [1,2,3,4,5,6,"taco"];
function reverse(array){
return array.map((item,idx) => array[array.length-1-idx])
}
20 bytes
let reverse=a=>[...a].map(a.pop,a)
const original = [1, 2, 3, 4];
const reversed = [...original].reverse(); // 4 3 2 1
Concise and leaves the original unchanged.
reveresed = [...array].reverse()
The shortest reverse method I've seen is this one:
let reverse = a=>a.sort(a=>1)
**
Shortest reverse array method without using reverse method:
**
var a = [0, 1, 4, 1, 3, 9, 3, 7, 8544, 4, 2, 1, 2, 3];
a.map(a.pop,[...a]);
// returns [3, 2, 1, 2, 4, 8544, 7, 3, 9, 3, 1, 4, 1, 0]
a.pop method takes an last element off and puts upfront with spread operator ()
MDN links for reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop
two ways:
counter loop
function reverseArray(a) {
var rA = []
for (var i = a.length; i > 0; i--) {
rA.push(a[i - 1])
}
return rA;
}
Using .reverse()
function reverseArray(a) {
return a.reverse()
}
This is what you want:
array.reverse();
DEMO
Here is a version which does not require temp array.
function inplaceReverse(arr) {
var i = 0;
while (i < arr.length - 1) {
arr.splice(i, 0, arr.pop());
i++;
}
return arr;
}
// Useage:
var arr = [1, 2, 3];
console.log(inplaceReverse(arr)); // [3, 2, 1]
I've made some test of solutions that not only reverse array but also makes its copy. Here is test code. The reverse2 method is the fastest one in Chrome but in Firefox the reverse method is the fastest.
var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var reverse1 = function() {
var reversed = array.slice().reverse();
};
var reverse2 = function() {
var reversed = [];
for (var i = array.length - 1; i >= 0; i--) {
reversed.push(array[i]);
}
};
var reverse3 = function() {
var reversed = [];
array.forEach(function(v) {
reversed.unshift(v);
});
};
console.time('reverse1');
for (var x = 0; x < 1000000; x++) {
reverse1();
}
console.timeEnd('reverse1'); // Around 184ms on my computer in Chrome
console.time('reverse2');
for (var x = 0; x < 1000000; x++) {
reverse2();
}
console.timeEnd('reverse2'); // Around 78ms on my computer in Chrome
console.time('reverse3');
for (var x = 0; x < 1000000; x++) {
reverse3();
}
console.timeEnd('reverse3'); // Around 1114ms on my computer in Chrome
53 bytes
function reverse(a){
for(i=0,j=a.length-1;i<j;)a[i]=a[j]+(a[j--]=a[i++],0)
}
Just for fun, here's an alternative implementation that is faster than the native .reverse method.
You can do
var yourArray = ["first", "second", "third", "...", "etc"]
var reverseArray = yourArray.slice().reverse()
console.log(reverseArray)
You will get
["etc", "...", "third", "second", "first"]
> var arr = [1,2,3,4,5,6];
> arr.reverse();
[6, 5, 4, 3, 2, 1]
array.reverse()
Above will reverse your array but modifying the original.
If you don't want to modify the original array then you can do this:
var arrayOne = [1,2,3,4,5];
var reverse = function(array){
var arrayOne = array
var array2 = [];
for (var i = arrayOne.length-1; i >= 0; i--){
array2.push(arrayOne[i])
}
return array2
}
reverse(arrayOne)
function reverseArray(arr) {
let reversed = [];
for (i = 0; i < arr.length; i++) {
reversed.push((arr[arr.length-1-i]))
}
return reversed;
}
Using .pop() method and while loop.
var original = [1,2,3,4];
var reverse = [];
while(original.length){
reverse.push(original.pop());
}
Output: [4,3,2,1]
I'm not sure what is meant by libraries, but here are the best ways I can think of:
// return a new array with .map()
const ReverseArray1 = (array) => {
let len = array.length - 1;
return array.map(() => array[len--]);
}
console.log(ReverseArray1([1,2,3,4,5])) //[5,4,3,2,1]
// initialize and return a new array
const ReverseArray2 = (array) => {
const newArray = [];
let len = array.length;
while (len--) {
newArray.push(array[len]);
}
return newArray;
}
console.log(ReverseArray2([1,2,3,4,5]))//[5,4,3,2,1]
// use swapping and return original array
const ReverseArray3 = (array) => {
let i = 0;
let j = array.length - 1;
while (i < j) {
const swap = array[i];
array[i++] = array[j];
array[j--] = swap;
}
return array;
}
console.log(ReverseArray3([1,2,3,4,5]))//[5,4,3,2,1]
// use .pop() and .length
const ReverseArray4 = (array) => {
const newArray = [];
while (array.length) {
newArray.push(array.pop());
}
return newArray;
}
console.log(ReverseArray4([1,2,3,4,5]))//[5,4,3,2,1]
As others mentioned, you can use .reverse() on the array object.
However if you care about preserving the original object, you may use reduce instead:
const original = ['a', 'b', 'c'];
const reversed = original.reduce( (a, b) => [b].concat(a) );
// ^
// |
// +-- prepend b to previous accumulation
// original: ['a', 'b', 'c'];
// reversed: ['c', 'b', 'a'];
Pure functions to reverse an array using functional programming:
var a = [3,5,7,8];
// ES2015
function immutableReverse(arr) {
return [ ...a ].reverse();
}
// ES5
function immutableReverse(arr) {
return a.concat().reverse()
}
It can also be achieved using map method.
[1, 2, 3].map((value, index, arr) => arr[arr.length - index - 1])); // [3, 2, 1]
Or using reduce (little longer approach)
[1, 2, 3].reduce((acc, curr, index, arr) => {
acc[arr.length - index - 1] = curr;
return acc;
}, []);
reverse in place with variable swapping (mutative)
const myArr = ["a", "b", "c", "d"];
for (let i = 0; i < (myArr.length - 1) / 2; i++) {
const lastIndex = myArr.length - 1 - i;
[myArr[i], myArr[lastIndex]] = [myArr[lastIndex], myArr[i]]
}
Reverse by using the sort method
This is a much more succinct method.
const resultN = document.querySelector('.resultN');
const resultL = document.querySelector('.resultL');
const dataNum = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const dataLetters = ['a', 'b', 'c', 'd', 'e'];
const revBySort = (array) => array.sort((a, b) => a < b);
resultN.innerHTML = revBySort(dataNum);
resultL.innerHTML = revBySort(dataLetters);
<div class="resultN"></div>
<div class="resultL"></div>
Using ES6 rest operator and arrow function.
const reverse = ([x, ...s]) => x ? [...reverse(s), x] : [];
reverse([1,2,3,4,5]) //[5, 4, 3, 2, 1]
Use swapping and return the original array.
const reverseString = (s) => {
let start = 0, end = s.length - 1;
while (start < end) {
[s[start], s[end]] = [s[end], s[start]]; // swap
start++, end--;
}
return s;
};
console.log(reverseString(["s", "t", "r", "e", "s", "s", "e", "d"]));
Infact the reverse() may not work in some cases, so you have to make an affectation first as the following
let a = [1, 2, 3, 4];
console.log(a); // [1,2,3,4]
a = a.reverse();
console.log(a); // [4,3,2,1]
or use concat
let a = [1, 2, 3, 4];
console.log(a, a.concat([]).reverse()); // [1,2,3,4], [4,3,2,1]
What about without using push() !
Solution using XOR !
var myARray = [1,2,3,4,5,6,7,8];
function rver(x){
var l = x.length;
for(var i=0; i<Math.floor(l/2); i++){
var a = x[i];
var b = x[l-1-i];
a = a^b;
b = b^a;
a = a^b;
x[i] = a;
x[l-1-i] = b;
}
return x;
}
console.log(rver(myARray));
JavaScript already has reverse() method on Array, so you don't need to do that much!
Imagine you have the array below:
var arr = [1, 2, 3, 4, 5];
Now simply just do this:
arr.reverse();
and you get this as the result:
[5, 4, 3, 2, 1];
But this basically change the original array, you can write a function and use it to return a new array instead, something like this:
function reverse(arr) {
var i = arr.length, reversed = [];
while(i) {
i--;
reversed.push(arr[i]);
}
return reversed;
}
Or simply chaning JavaScript built-in methods for Array like this:
function reverse(arr) {
return arr.slice().reverse();
}
and you can call it like this:
reverse(arr); //return [5, 4, 3, 2, 1];
Just as mentioned, the main difference is in the second way, you don't touch the original array...
How about this?:
function reverse(arr) {
function doReverse(a, left, right) {
if (left >= right) {
return a;
}
const temp = a[left];
a[left] = a[right];
a[right] = temp;
left++;
right--;
return doReverse(a, left, right);
}
return doReverse(arr, 0, arr.length - 1);
}
console.log(reverse([1,2,3,4]));
https://jsfiddle.net/ygpnt593/8/

Categories

Resources