How can I make a reversed copy of an array using .reverse()? I can't wrap my head around this.
This is my function:
function flipArray(inputArray){
let origArray = inputArray;
let flippedArray = origArray.reverse();
console.log(inputArray);
console.log(origArray);
console.log(flippedArray);
}
flipArray([1,2,3]);
I would expect this...
[1, 2, 3]
[1, 2, 3]
[3, 2, 1]
or this...
[1, 2, 3]
[3, 2, 1]
[3, 2, 1]
but this is what I get...
[3, 2, 1]
[3, 2, 1]
[3, 2, 1]
Why does even inputArray get reversed? Is there another way to do this apart from a for loop?
Array.prototype.reverse reverse the array in-place. It modifies the original array and returns a reference to it. In order to create copies of the original array before it is reversed, you could use Array.prototype.slice, for example:
function flipArray(inputArray){
let origArray = inputArray.slice(0);
let flippedArray = inputArray.slice(0).reverse();
console.log(inputArray);
console.log(origArray);
console.log(flippedArray);
}
flipArray([1,2,3]) now produces
[1,2,3]
[1,2,3]
[3,2,1]
Related
How to get which do not intersect value between 2 Array with Lodash?
Expected:
const arr1 = [1, 2, 3]
const arr2 = [2, 3, 4]
console.log(unintersection(arr1, arr2))
Output
[1, 4]
Use _.xor() to find the symmetric difference - the numbers that are in one of the arrays, but not both:
const arr1 = [1, 2, 3]
const arr2 = [2, 3, 4]
const result = _.xor(arr1, arr2)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
var arr = [1, 2, 3, 4, 5]
console.log(arr)
//[1, 2, 3, 4, 5]
arr = arr.splice(4, 1)
console.log(arr)
//[5]
I want to remove only the last element. Why does it remove every element except the last one?
You need to omit the assignment.
var arr = [1, 2, 3, 4, 5]
console.log(...arr); // [1, 2, 3, 4, 5]
arr.splice(4, 1);
console.log(...arr); // [1, 2, 3, 4]
If you like just to delete the last one, you could take a negative index with Array#splice. This works for any other index from the end.
var arr = [1, 2, 3, 4, 5]
console.log(...arr); // [1, 2, 3, 4, 5]
arr.splice(-1, 1);
console.log(...arr); // [1, 2, 3, 4]
Array#splice modifies the array in place and returns the removed portion. You should not reassign the removed portion to the variable.
var arr = [1, 2, 3, 4, 5]
arr.splice(4, 1)
console.log(arr);
splice alters the array and returns the removed item(s) in a new array.
By the way, you should use pop which is better suited for this like so:
var arr = [1, 2, 3, 4, 5];
arr.pop();
console.log(arr);
pop removes the last item of the array.
This is a more general approach:
var arr = [1, 2, 3, 4, 5]
arr.splice(arr.length - 1);
console.log(arr)
You can access to the last arr element by splice(-1), then you stored that value (5) into a variable (newArr). The original array now values [1, 2, 3, 4].
let arr = [1, 2, 3, 4, 5];
let newArr = arr.splice(-1);
console.log(arr) //[1, 2, 3, 4]
console.log(newArr) //[5]
The splice method takes two parameters: a beginning index (inclusive) and an ending index (exclusive). The below will do what you described.
arr = arr.splice(0, 4)
In your code, you are reassigning the arr to the spliced value, which is [5]. the way you should do it is,
var arr = [1, 2, 3, 4, 5]
console.log(arr)
//[1, 2, 3, 4, 5]
arr.splice(4, 1)
console.log(arr)
//[1, 2, 3, 4]
This should give you the result you are looking for;
The splice() method adds/removes items to/from an array, and returns the removed items in the form of an array.
Syntax :
let arrDeletedItems = array.splice(starting_index , index to which you want to add or remove an item , item 1 , item 2 , item 3 ...so on )
let arr = [1, 2, 3, 4, 5]
arr.splice(4, 1)
so in your case, you are starting from index 4 which means the value "5" and you are removing the 1st element that starts from index 4 which is the value '5'. So the splice method would return a new array (as it returns a new array of the removed elements) containing only 5.
To get back an array containing all the elements except the last element 5 you should write :
arr = arr.splice(0,4)
which means that start from index 0 and remove elements till index 4.
Splice method returns the removed item(s) in an array so what is happening is you are assigning the returned to the original array. Instead do this
var arr = [1, 2, 3, 4, 5];
console.log(arr);
//[1, 2, 3, 4, 5]
arr.splice(4, 1);
console.log(arr);
Splice modifies array in place and returns removed part as a new array.
To get expected result you want to use expression:
var arr = [1, 2, 3, 4, 5]
console.log(arr)
//[1, 2, 3, 4, 5]
arr.splice(4, 1)
console.log(arr)
//[5]
You can also remove the last element from the array with rest operator
const array = [1, 2, 3, 4, 5]
const [ ...newArray, last ] = array
I'm trying to swap the two lowest values in a shuffled array containing the numbers 0-14. For those curious, I'm implementing the shuffling algorithm for a 15 puzzle described by pkpnd here.
I wanted to try destructuring assignment, as described here, but am encountering an unexpected behavior. I realize that I can get my code working (and make it more readable) by just creating a temporary variable, but I'd like to understand what's happening before moving on.
I'm grabbing a subset of my array [1,2] and then trying to replace it with [2,1]. For some reason, it's only swapping the values when their order in the original array is opposite of the order of my subset.
I originally tried this:
var arr1 = [1, 2, 3, 4];
var arr2 = [2, 1, 3, 4];
[arr1[arr1.indexOf(1)], arr1[arr1.indexOf(2)]] = [arr1[arr1.indexOf(2)], arr1[arr1.indexOf(1)]];
[arr2[arr2.indexOf(1)], arr2[arr2.indexOf(2)]] = [arr2[arr2.indexOf(2)], arr2[arr2.indexOf(1)]];
console.log("arr1: " + arr1, "\narr2: " + arr2);
And then tried this:
var arr1 = [1, 2, 3, 4];
var arr2 = [2, 1, 3, 4];
[arr1[arr1.indexOf(1)], arr1[arr1.indexOf(2)]] = [2, 1];
[arr2[arr2.indexOf(1)], arr2[arr2.indexOf(2)]] = [2, 1];
console.log("arr1: " + arr1, "\narr2: " + arr2);
But both produce identical output:
arr1: 1,2,3,4
arr2: 1,2,3,4
I would expect that the position of 1 and 2 would be swapped for both arrays, but they're only swapped in arr2. I suspect this has to do with they way the initial array subset [1,2] is created, but I'm not sure.
Can anybody explain why the values aren't always swapped?
The result is simple, because it goes step for step for each item of destructuring assingment. And while the values are changing, the index of the values changes.
Case 1 [1, 2, 3, 4]
Get index of target for the first value 2
[arr1[arr1.indexOf(1)], arr1[arr1.indexOf(2)]] = [2, 1];
// ^^^^^^^^^^^^^^^ 0
Assign 2 to arr1[0]
[2, 2, 3, 4]
Get index of target for the second value 1:
[arr1[arr1.indexOf(1)], arr1[arr1.indexOf(2)]] = [2, 1];
// ^^^^^^^^^^^^^^^ 0
Assign 1 to arr1[0]
[1, 2, 3, 4]
Case 2 [2, 1, 3, 4]
Get index of target for the first value 2
[arr2[arr2.indexOf(1)], arr2[arr2.indexOf(2)]] = [2, 1];
// ^^^^^^^^^^^^^^^ 1
Assign 2 to arr1[1]
[2, 2, 3, 4]
Get index of target for the second value 1:
[arr2[arr2.indexOf(1)], arr2[arr2.indexOf(2)]] = [2, 1];
// ^^^^^^^^^^^^^^^ 0
Assign 1 to arr1[0]
[1, 2, 3, 4]
I have the following function which is supposed to remove the smallest value from an array, but if this is a duplicate it will just remove the first one and leave the others.
var array1 = [1, 2, 3, 4, 5];
var array2 = [5, 3, 2, 1, 4];
var array3 = [2, 2, 1, 2, 1];
function removeSmallest(numbers) {
return numbers.filter(function(elem, pos, self) {
if(elem == Math.min.apply(null, numbers) && pos == self.indexOf(elem)) {
// Remove element from Array
console.log(elem, pos);
numbers.splice(pos, 1);
};
return numbers;
});
};
Via console.log(elem, pos) I understand that I have correctly identified the smallest and first element in the array, but when I try to remove it through splice(), I end up getting the following result for the arrays:
array1 = [1, 3, 4, 5]; // But I expected [2, 3, 4, 5]
array2 = [5, 3, 2, 1]; // But I expected [5, 3, 2, 4]
array3 = [2, 2, 1, 1]; // But I expected [2, 2, 2, 1]
Do you know what is the issue with my code? Thanks in advance for your replies!
function removeSmallest(numbers) {
const smallest = Math.min.apply(null, numbers);
const pos = numbers.indexOf(smallest);
return numbers.slice(0, pos).concat(numbers.slice(pos + 1));
};
You shouldn't use filter() the way you do. It's also a good practice that a function should return a new array rather than modifying the existing one and you definitely shouldn't modify an array while iterating over it.
function removeSmallest(arr){
var temp=arr.slice(),smallElement=null;
temp.sort(sortReverse);
smallElement=temp[temp.length-1];
var position=arr.indexOf(smallElement);
arr.splice(pos,1);
console.log(arr);
}
function sortReverse (a,b){
if(a<b){return 1}
else if(a>b){return -1;}
else{return 0;}
}
var array1 = [1, 2, 3, 4, 5];
removeSmallest(array1);
I normally use while loop as:
while (i<some_value)
I saw while(i--) syntax and thought it is shorter and cooler and tried the following in google-chrome.
var num_arr= [4,8,7,1,3];
var length_of_num_arr=num_arr.length;
while(length_of_num_arr--) console.log(num_arr);
[4, 8, 7, 1, 3]
[4, 8, 7, 1, 3]
[4, 8, 7, 1, 3]
[4, 8, 7, 1, 3]
[4, 8, 7, 1, 3] **// THIS IS EXPECTED RESULT**
But When I try...
while((num_arr.length)--) console.log(num_arr);
[4, 8, 7, 1]
[4, 8, 7]
[4, 8]
[4]
[] // WHY IS THIS HAPPENING??
Is there some hidden things you need to understand to use this syntax?
Arrays’ length property is writable, and will cut off their elements or add empty slots as appropriate when you set it.
var items = [1, 2, 3, 4, 5];
items.length = 3; // items is now [1, 2, 3]
items.length = 6; // items is now a sparse array: [1, 2, 3, undefined × 3]
So, don’t do that.
When you do array.length-- you're potentially shortening the array by one element each time.
See the reference under the section Shortening the array from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length
Array.prototype.length can be re-written programmatically and it potentially shorten your array by the new length you assign.
For example
a = [1,2,3,4,5,6,7,8,9,10];
// Shorten the array by one element
a.length--; // a <-- [1,2,3,4,5,6,7,8,9]
// In case you want to shorten your array to 3 elements, you can:
a.length = 3; // a <-- [1,2,3]
When you set the length property of an array to a lower value, the items at the end are removed:
var arr = [1,2,3,4,5];
arr.length; // 5
arr.length = 3;
arr; // [1,2,3]
This is described in the spec:
While newLen < oldLen repeat,
Set oldLen to oldLen – 1.
Let deleteSucceeded be the result of calling the [[Delete]] internal method of A passing ToString(oldLen) and false
as arguments.
In your code you use the postfix decrement operator (--) which reduces the length of the array.