This question already has answers here:
Why can't direcrlty return a value by using .push() in javascript?
(2 answers)
Closed 5 years ago.
Can someone please help me understand whats going on here?
let firstArray = [];
firstArray.push(1);
firstArray.push(1);
firstArray.push(1);
console.log("firstArray", firstArray); // result [ 1, 1, 1 ] - as expected.
let secondArray = [1, 2, 3].reduce((acc, item) => {
console.log("acc", acc);
console.log("typeof acc", typeof acc);
// on first passing, the accumulator (acc) is Array[] == object.
// on the second passing the acc == number.
// but why?
/// i expect to get [1,1,1] as my secondArray.
return acc.push(1);
}, []);
console.log("secondArray", secondArray);
the program crashes with "acc.push is not a function"
And inspecting the first logged accumulator shows that we have the push method - it's a real function:
The return value of Array#push is the new length of the array after the push. This means that in the second iteration acc is a number, which doesn't have the push method.
The fix is simple - separate the push and return statements:
const secondArray = [1, 2, 3].reduce((acc, item) => {
acc.push(1);
return acc;
}, []);
console.log(secondArray);
Related
I'm trying to find the 2nd largest number in an array, and square this number.
arr = [1,8,6,2,5,4,8,3,7] should return 49 (7 squared)
arr = [1,1] should return 1 (1 squared)
I've tried the code below and it works on the first array and return 49, but on the second array with [1,1] it returns NaN.
The problem is with the secondLargest variable--it returns undefined on the console.log. It may be because I'm using set, but I don't understand why it's not just returning 1 instead of undefined.
var maxArea = function(height) {
let secondLargest = Array.from([...new Set(height)]).sort((a,b) => b-a)[1]
console.log(secondLargest);
return Math.pow(secondLargest, 2);
};
Set eliminates duplicates, so the array [1, 1] gets turned into [1]. There is no second element, so you get undefined when trying to access index 1. Since this is not what you want, sort the array directly without creating a Set, or take the first element when there is no second element.
function maxArea(height) {
const sorted = [...new Set(height)].sort((a,b) => b-a);
return (sorted[1] ?? sorted[0]) ** 2;
}
console.log(maxArea([1, 1]));
console.log(maxArea([1,8,6,2,5,4,8,3,7]));
This question already has answers here:
Fastest way to move first element to the end of an Array
(9 answers)
How to get the first element of an array?
(35 answers)
Closed 5 months ago.
I have an array which I have sorted from smallest integer to largest. The array data comes from backend and will be random numbers
// example array from backend
const arr = [400,30,10,-1]
const sortedArray = arr.sort((a, b) => a - b)
// [-1,10,30,400]
If the first index of the array is equal to -1 I want to remove it from the first position in the array and append it to the last position of the array.
For example if array is [-1, 10, 30, 400] I want to return [10,30,400,-1].
Edit: I am looking for the safest possible way and unsure to use splice(), filter() etc
shift the first element off the array and push it on the end.
const arr = [400,30,10,-1].sort();
if (arr[0] === -1) arr.push(arr.shift());
console.log(arr);
After your code you can check first element is -1 and then slice and push -1 to it
if(arr[0] == -1){
arr = arr.slice(1)
arr.push(-1)
}
I might have exaggerated the solution, but I am guessing it might help someone.
const beData = [400, 30, 10, -1];
const sortedData = beData.sort((a, b) => a - b);
const newArr = sortedData.reduce((prevValue, currValue) => {
if(currValue < 0) {
prevValue[1].push(currValue);
} else {
prevValue[0].push(currValue);
}
return prevValue;
}, [[], []]);
const result = [...newArr[0], ...newArr[1]];
console.log(result);
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.
Can someone please explain why the function is behaving differently in the following two scenarios? In the first scenario error is prompted saying 'arr.push is not a function'.
scenario 1
const arr = [1, 3, 11];
const doubled = arr.reduce((doubledArr, item) => {
return doubledArr.push(item * 2);
}, []);
console.log(doubled);
scenario 2
const arr = [1, 3, 11];
const doubled = arr.reduce((doubledArr, item) => {
doubledArr.push(item * 2);
return doubledArr
}, []);
console.log(doubled);
In the first scenario you return the result of Array.push(), which is the new length property of the object (the accumulator array) upon which the method was called. On the next iteration of Array.reduce(), this number is provided as the accumulater and you try again to push a value to it. Since it's no longer an array but a number, you get the error arr.push is not a function.
The Array.reduce() callback should always return the accumulator, same as you did in scenario 2.
This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 3 years ago.
Let's say I have this Object of arrays:
foo = {morning: [1,2,3,4,5], afternoon: [1,2,3,4,7]}
I want to write a function that returns this object but remove a particular value.
ex: I want to remove the number 3 in afternoon.
The function would return {morning: [1,2,3,4,5], afternoon: [1,2,4,7]}
myFunction = (partsOfDay, number) => {
// do something
// returns the object of arrays but without the specified value
}
How can I do that ?
You can do this without changing the source object using Array.reduce() and Object.entries().
The properties of the returned object will still point to the source object but the filtered array properties will be copied with Array.filter().
const foo = { morning: [1,2,3,4,5], afternoon: [1,2,3,4,7] };
const myFilter = (obj, prop, value) => Object.entries(obj).reduce((acc, [key, val]) => {
acc[key] = key === prop && Array.isArray(val) ? val.filter(x => x !== value) : val;
return acc;
}, {});
console.log(myFilter(foo, 'afternoon', 3));
console.log(myFilter(foo, 'morning', 3));
console.log(foo);
There are many ways, something like this
var partsOfDay = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
myFunction = (partsOfDay, number) => {
var filtered = partsOfDay.filter(function(value, index, arr){
return value != number;
});
}
Refer for more here