Array destructuring in prototype function parameters [duplicate] - javascript

This question already has answers here:
SyntaxError Unexpected token, expected ","
(1 answer)
The use of brackets in javascript arrow function declaration
(1 answer)
Syntax for destructuring arrays into function parameters in ES6
(1 answer)
Closed 1 year ago.
Is there a way in which I can destructure an array in the parameters of its prototype functions?
For example, I can use an Array.prototype function such as forEach to evaluate the value of each array element and log an individual sub-array value using bracket notation:
const array = [[0,1],[3,4],[5,6]];
array.forEach(element => console.log(element[0]));
// -> 0
// -> 3
// -> 5
If I want to refer to a sub-array element by an assigned name, can I do so with destructuring? Currently, I know I can do it like this:
let array = [[0,1],[3,4],[5,6]];
array.forEach(element => {
let first = element[0];
let second = element[1];
console.log(first);
// -> 0
// -> 3
// -> 5
});
What I would like to achieve using destructuring is assigning these variable names the way you normally would with destructuring in a typical function's parameters:
let array = [[0,1],[3,4],[5,6]];
array.forEach([first, second] => console.log(first));
// Uncaught SyntaxError: Malformed arrow function parameter list
Is this possible?

After a little bit of trial and error, it appears this is fully possible. You just have to wrap the restructuring parameter in parentheses the same way you would if there were multiple parameters:
let array = [[0,1],[3,4],[5,6]];
array.forEach(([first, second]) => console.log(first));
// -> 0
// -> 3
// -> 5

Related

Reduce function only working once in JavaScript code [duplicate]

This question already has answers here:
How to call reduce on an array of objects to sum their properties?
(23 answers)
Closed 2 years ago.
I currently have to functions which use the Array.reduce method but only the first function works.
let profit = incomes.reduce((a,b) => a.getAmount() + b.getAmount());
Where a = a custom BudgetItem class with the method getAmount. I am wondering if this is a common JS thing or if I am doing something wrong.
Please note I have checked with the debugger and entering this line I have the same data in both methods.
According to mozilla the first parameter in Array.reduce() is the accumulator (the current sum) and the second is the current value from the array
arr.reduce(callback( accumulator, currentValue, [, index[, array]] )[, initialValue])
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
So if you are trying to total the value from an array of BudgetItem you will want something like:
let profit = incomes.reduce((currentTotal, curremtIncome) => currentTotal + curremtIncome.getAmount());

How to access a particular path/adress inside an object? [duplicate]

This question already has answers here:
access object through dot-syntax string path
(2 answers)
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 2 years ago.
I am having a problem which I think I might have figured out before how to do it but I can't remember now and can't figure it out.
Let's say we have an object thats a few levels deep, meaning it has as values other objects which also have as some of the values objects and so on.
Now how could I make a function to which I pass the object and and adress inside it and I can access the value at that location inside the function like this:
const getValueAtAdress = (object, 'country.city.rules') => {
return //here I need to return the value at object.country.city.rules.
}
Am I missing something obvious?
I thought I'd mention here for posterity that what helped me was the answer using the reduce which is exactly what I used before but I could not remember:
Example that I am using for my particular problem:
let stateLocation = address.split('.').reduce((acc, cur) => acc[cur], state);
Your code shows a function declaration but you can't declare an argument name in quotes
You can however call a function and pass a string.
In that case, you just need to split the string into an array and then loop over that array, building up a "chained" set of string indexes that can be passed to the object. The String.split() and Array.reduce() methods are the key.
let obj = {
county: {
city: {
rules: "Strict"
}
}
};
const getValueAtAddress = (object, countyCityRules) => {
// Split the string at the dots to form an array...
// The loop over that array and reduce it with an
// accumulator that is then applied to the object.
return countyCityRules.split(".").reduce((acc, cur) => acc[cur], obj);;
}
console.log(getValueAtAddress(obj, "county"));
console.log(getValueAtAddress(obj, "county.city"));
console.log(getValueAtAddress(obj, "county.city.rules"));

why `new Array(5).map((x,y)=>y*2)` didn't work? while `new Array(5).fill(1).map((x,y)=>y*2)` work? [duplicate]

This question already has answers here:
JavaScript "new Array(n)" and "Array.prototype.map" weirdness
(14 answers)
Closed 3 years ago.
I was trying to create an array which is [1,2,3,...,n], so I used code new Array(10).map((value,index)=>index+1), but I got [empty × 5];
Meanwhile, new Array(10).fill(1).map((value,index)=>index+1), why?
How did Array.prototype.map() work?
My code:
// [empty × 10]
new Array(10).map((value,index)=>index+1)
// [1,2,...,10]
new Array(10).fill(1).map((value,index)=>index+1)
As per MDN docs:
map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).
In your first case, You are just creating an array of a certain length without setting any value so it won't call the map callback. In the second method, you are setting all values to 1 using Array#fill method so it will call the callback since the value is assigned for all index.
You can use Array.from method with a map callback for generating an array.
const arr = Array.from({ length: 10 }, (_, i) => i + 1)
console.log(arr)

How to pass arguments to a function from a wrapper function in ES6 [duplicate]

This question already has answers here:
Official information on `arguments` in ES6 Arrow functions?
(2 answers)
Closed 6 years ago.
function foo(x) {
console.log(arguments)
} //foo(1) prints [1]
but
var bar = x => console.log(arguments)
gives the following error when invoked in the same way:
Uncaught ReferenceError: arguments is not defined
Arrow functions don't have this since the arguments array-like object was a workaround to begin with, which ES6 has solved with a rest parameter:
var bar = (...arguments) => console.log(arguments);
arguments is by no means reserved here but just chosen. You can call it whatever you'd like and it can be combined with normal parameters:
var test = (one, two, ...rest) => [one, two, rest];
You can even go the other way, illustrated by this fancy apply:
var fapply = (fun, args) => fun(...args);

Difference between "new Array(..)" and "[..]" in JavaScript? [duplicate]

This question already has answers here:
What’s the difference between "Array()" and "[]" while declaring a JavaScript array?
(19 answers)
Closed 8 years ago.
Is
var myCars=new Array("Saab","Volvo","BMW");
and
var myCars=["Saab","Volvo","BMW"];
exactly the same ?
Yes, for that case they are the same.
There is a difference if you have only one item, and it's numeric. This will create an array with a single item:
var myNumbers = [42];
but this will create an array with the length 42:
var myNumbers = new Array(42);
Yes, they are. However be aware that when you pass just a single numeric parameter to the Array constructor, you will be specifying the initial length of the array, instead of the value of the first item. Therefore:
var myCars1 = new Array(10);
... will behave differently from the following array literal:
var myCars2 = [10];
... note the following:
console.log(myCars1[0]); // returns undefined
console.log(myCars1.length); // returns 10
console.log(myCars2[0]); // returns 10
console.log(myCars2.length); // returns 1
That is one reason why it is often recommended to stick to the array literal notation: var x = [].
Yes, they are the same. There is no primitive form of an Array, as arrays in JavaScript are always objects. The first notation (new Array constructor syntax) was used heavily in the early days of JavaScript where the latter, short notation was not supported well.
Note that there is one behavioural difference: if you pass a single, numeric argument to new Array, like new Array(20), it will return a new array pre-initialised with that number of elements from 0 to n - 1, set to undefined.

Categories