what's wrong with this sort function? javascript [duplicate] - javascript

This question already has answers here:
Why does Array.prototype.push return the new length instead of something more useful?
(6 answers)
Closed 1 year ago.
I want to find out the index of the element which is the lowest number in the array.
For ex: function getIndexToIns([3, 2, 10, 7], 4) will return 2 because if 4 is inserted into the array, the array should be [2, 3, 4, 7, 10] following ascending order. And 4 has the index of 2.
And my code snippet is as below and it shows error "TypeError: newArr.sort is not a function"
function getIndexToIns(arr, num) {
newArr = arr.push(num);
newArr.sort((a, b) => a-b);
return newArr.indexOf(num)
}
getIndexToIns([2, 10, 4], 50);
console.log(getIndexToIns([2, 10, 4], 50))
What is wrong in my code snippet???

.push() modifies the array in place, it does not return a new array. So newArray isn't an array.
You can create a new array with something like:
let newArr = [...arr, num];
Or perhaps:
let newArr = arr.concat([num]);

Welcome.
Remove newArr in newArr = arr.push(num); to become
arr.push(num);
Push method doesn't return the array itself but the new length. Ref

See documentation for Array.prototype.push():
The push() method adds one or more elements to the end of an array and
returns the new length of the array.
On top of that, push and sort methods mutate your original array. You should define your newArr like this:
const newArr = [...arr, num];
Then you can sort it and find out the index of element like you do it now.

Related

Leetcode Rotate Array works differently in codepen [duplicate]

This question already has answers here:
Rotate the elements in an array in JavaScript
(42 answers)
Closed 2 months ago.
I've solved one of Leetcode problems in codepen, but when I try to submit it on leetcode I get a different result than what I get in codepen.
The problem is:
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Link (requires login) https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/646/
My solution:
var rotate = function(nums, k) {
var a = nums.splice(0 , nums.length-k);
var b = nums.splice(-k);
var c = [...b , ...a ];
return(c);
};
Using the above example, running this code on codepen returns (or console.logs) [5,6,7,1,2,3,4].
But when I run this code in leetcode, I get an empty array [].
Any ideas why this could be the happening?
It looks like you're supposed to rotate the original array, not return a new rotated array. So you need to set nums = [...b, ...a] instead.
EDIT: Since JavaScript passes by value, the nums parameter just holds a reference to the original array, so doing nums = [] will only change the nums variable to reference a different array, without changing the original array. You'll want to call methods of the original array to mutate it. E.g. .splice
/EDIT
Also, have you thought about what happens when k is greater than the length of the array? E.g. nums = [1, 2, 3], k = 5
Also also, your link to leetcode requires login, so not everyone will be able to view it.
Example A
.pop() removes the last element of an array and returns it. .unshift() the returned value of .pop() to the first index of the array. Do that k times in a for loop. .pop() and .unshift() changes (aka mutates) the original array.
let arr = [1, 2, 3, 4, 5, 6, 7], k = 3;
function rotate(array, times) {
for (let i=0; i < times; i++) {
let last = array.pop();
array.unshift(last);
}
return array;
}
console.log(rotate(arr, k));
Example B
By changing .splice() to .slice() you can implement your logic since .slice() creates a shallow copy of the array and does not mutate the original array like .splice(). Since the original array is unchanged, any references to said array are consistent. Also, concerning the case mentioned in LawrenceWebDev's answer -- if k is greater than the length of the array -- k (times) becomes the remainder of k/array.length (times % size).
let arr = [1, 2, 3, 4, 5, 6, 7], k = 3;
function rotate(array, times) {
const size = array.length;
if (times > size) {
times = times % size;
}
let a = array.slice(-times);
let b = array.slice(0, size - times);
return [...a, ...b];
}
console.log(rotate(arr, k));

Return the biggest number in the array (array contains a string)?

I dont understand why my code is not working, when I read it logically I feel that it should work, but what it does is return 3,4,2 as opposed to the highest number of the 3 (i.e. 4)
const array2 = ['a', 3, 4, 2] // should return 4
for(items of array2){
if(items > 0) {
console.log(Math.max(items));
}
What am I doing wrong? What have I misinterpreted? Please don't give me the answer, just tell me why my logic does'nt work
in for-loop, items is just one item actually. Each time, you print the current item. it is basically the same thing with this
const array2 = ['a', 3, 4, 2] // should return 4
for(items of array2){
if (items > 0) {
console.log(items);
}
}
you can do it with this only
const array2 = ['a', 3, 4, 2] // should return 4
console.log(Math.max(...array2.map(s => +s || Number.MIN_SAFE_INTEGER)));
check out: https://stackoverflow.com/a/44208485/16806649
if it was integer-only array, this would be enough:
const array2 = [3, 4, 2] // should return 4
console.log(Math.max(...array2));
You just need to filter the array.
Below example I am using filter() method of array and then just pass that filteredarray to Math.max() function.
isNan() function returns false for valid number.
Math.max(...filteredArr) is using spred operator to pass the values.
const arr = ['a', 3, 4, 2];
const filteredArr = arr.filter(val => {
if (!isNaN(val)) return val;
})
console.log(Math.max(...filteredArr));
I don't think you need the "For(items of arr)" instead just if the length of the array is greater than 0, then console.log(Math.max(...arr) should work.
See document ion below:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
It is returning 3,4,2 because you are taking array2, and iterating through with each individual element of the array. items is not the entire array, it is the individual element and that is why Math.max of an individual element is just getting the same value.
just you need fliter you're array then get max value, also in arrayFilters function use to removes everything only return numbers of this array
function arrayFilters(array){
const number = array.filter(element => typeof element === 'number')
return number;
}
function getMaxValue(number){
return Math.max.apply(null,number)
}
const arr = ['a',2,3,4];
console.log(getMaxValue(arrayFilters(arr)))

Spinning the elements of an array clockwise in JS

I am supposed to rotate an array of integers clockwise in JS.
Here is my code for it:
function rotateArray(N, NArray)
{
//write your Logic here:
for(j=0;j<2;j++){
var temp=NArray[N-1];
for(i=0;i<N-1;i++){
NArray[i+1]=NArray[i];
}
NArray[0]=temp;
}
return NArray;
}
// INPUT [uncomment & modify if required]
var N = gets();
var NArray = new Array(N);
var temp = gets();
NArray = temp.split(' ').map(function(item) { return parseInt(item, 10);});
// OUTPUT [uncomment & modify if required]
console.log(rotateArray(N, NArray));
The code accepts an integer N which is the length of the array. The input is as follows:
4
1 2 3 4
The correct answer for this case is supposed to be
4 1 2 3
But my code returns
4 1 1 1
I cannot find where my code is going wrong. Please help me out.
All you need to do is move one item from the end of the array to the beginning. This is very simple to accomplish with .pop() (removes an item from the end of an array), then declare a new array with that element as the first:
function rotateArray(N, NArray) {
const lastItem = NArray.pop();
return [lastItem, ...NArray];
}
console.log(rotateArray(1, [1, 2, 3, 4]));
Doing anything else, like using nested loops, will make things more unnecessarily complicated (and buggy) than they need to be.
If you don't want to use spread syntax, you can use concat instead, to join the lastItem with the NArray:
function rotateArray(N, NArray) {
const lastItem = NArray.pop();
return [lastItem].concat(NArray);
}
console.log(rotateArray(1, [1, 2, 3, 4]));
If you aren't allowed to use .pop, then look up the last element of the array by accessing the array's [length - 1] property, and take all elements before the last element with .slice (which creates a sub portion of the array from two indicies - here, from indicies 0 to the next-to-last element):
function rotateArray(N, NArray) {
const lastItem = NArray[NArray.length - 1];
const firstItems = NArray.slice(0, NArray.length - 1);
return [lastItem].concat(firstItems);
}
console.log(rotateArray(1, [1, 2, 3, 4]));
function rotate(array,n){
Math.abs(n)>array.length?n=n%array.length:n;
if(n<0){
n=Math.abs(n)
return array.slice(n,array.length).concat(array.slice(0,n));
}else{
return array.slice(n-1,array.length).concat(array.slice(0,n-1));
}
}
console.log(rotate([1, 2, 3, 4, 5],-3));
The answer by #CertainPerformance is great but there's a simpler way to achieve this. Just combine pop with unshift.
let a = [1,2,3,4];
a?.length && a.unshift(a.pop());
console.log(a);
You need to check the length first so you don't end up with [undefined] if you start with an empty array.

Shorter way to remove an item by index from an array [duplicate]

This question already has answers here:
How to delete an item from state array?
(18 answers)
Closed 5 years ago.
I've made this post last year and today, I assume things can be simplified.
I need to remove an item from an array but by the index. When by the index, it does not matter if the array has same values. Your typical example:
let arr = [1,2,3,2,1] // just an array, not array with objects
let x = 1;
// This will not be an expected result:
// Find all values that is equal to 1 then remove
arr.filter(num => num !== x) //=> [2,3,2]
My expectation is when I remove the last element (1), for example, the array should be [1,2,3,2]:
let index = 4; // which is the last "1" in the array
let indexVal = arr.indexOf(4) // 1
let newArray = arr.splice(indexVal, 1) //=> [1,2,3,2]
Now, it's 2017, almost '18, is there a shorter way (es5/6) of doing this without any polyfil?
Edit:
Think of this as a todo:
<ul>
<li>me</li>
<li>me</li> // click to delete this one
<li>you</li>
<li>me</li>
</ul>
To correctly remove that item, I have to delete by the index not value
The Array.filter callback gives 2 arguments, number and index and you can filter the array this way.
let arr = [1,2,3,2,1]
let x = 4; //suppose you want to remove element at 4th index
let editedArray = arr.filter((num, index) => index !== x) //editedArray = [1,2,3,2]
EDIT:
The third parameter gives the whole array. Thanks #Oliver for pointing this out in comment
arr.splice(index, 1);
or if you specifically want to remove the last element:
arr.pop();
No indexOf call. The indexOf call never should have been there; it only ever looked like it worked because indexOf returns -1 for an element that isn't present, and splice treats negative indices as counting from the end of the array.
Also, splice modifies the array in place and returns an array of removed elements, so assigning its return value the way you were doing is misleading.
The only way I can think of is the one we use in Redux every day:
const arr = [1, 2, 3, 2, 1]
const index = 4 // index of the item you want to remove
const newArr = [...arr.slice(0, index), ...arr.slice(index + 1)]
console.log(newArr) // [1, 2, 3, 2]
It might not be the shortest but it is more 2017 and it is immutable, which is very important!
Ajay's answer might be what you're looking for. Anyway, there are people like me who prefer slightly-more-lines-but-more-readable/rewritable/maintable solution, I'd do it this way:
function removeElementByIndex(arr, x) {
var newArr = [];
for(var i = 0; i < arr.length; i++) {
if(i != x) {
newArr.push(arr[i]);
}
}
return newArr;
}
// Usage
removeElementByIndex([1, 2, 3, 2, 1], 4);// outputs: [1, 2, 3, 2]
Now, it's 2017, almost '18, is there a shorter way (es5/6) of doing
this without any polyfil?
LOL! Many basic things not yet implemented. We'll have to wait for 2118 or another programming language to replace JS (oh wait, there's one, aka jQuery :P ).

How to remove an item from a list without distorting the original list

This is what I'm trying to do, I have an array
var arr = [1, 2, 3, 4, 5];
then I want to create a new array each time by removing an item once i.e when i remove item at index 0 i should have [2, 3, 4, 5]and when i remove an item at index 1, I should have [1, 3, 4, 5] and so on till i get to arr.length-1 and each time i remove an item i still want my arr to be intact unchanged
using javaScript I have tried some array methods like splice, slice but all that changes the value of arr
how do i go about it with either javascript or python.
For Javascript, using ES6 array spread operator and slice method,
var new_array = [...a.slice(0, index), ...a.slice(index + 1)];
const cut = (a, i) => [...a.slice(0, i), ...a.slice(i + 1)];
let arr = [2, 2, 2, 4, 2];
console.log(cut(arr, 3));
console.log(arr);
For Python:
array = [1,2,3,4,5];
newarray = [value for counter, value in enumerate(array) if counter != 0 ]
PS each time you will use this list-comprehension, array will not be modified! so basically you will get the same output for newarray.
If you want to have newarray each time removed one element you need to create a function instead of list-comprehension (of course it's possible but will likely be less readable).
For JavaScript:
Try making a copy with slice() (slice returns a shallow copy of the array that you can manipulate without affecting the original array) and then using splice() to remove the value at your desired index:
newArray = slice(arr).splice(index, 1);

Categories

Resources