This question already has answers here:
What is the difference when we use array names instead of spread operator?
(3 answers)
Closed 4 years ago.
Consider a scenario where in you are trying to iterate over a const array.
Would there be any difference between
[...arr].forEach((elem) => {
// your operations
});
and
arr.forEach((elem) => {
// your operations
});
Can these two be used interchangeably?
It will make a copy of the array. If the callback function would use the array parameter and it would modify it, that would make a difference. E.g.:
[...arr].forEach((val, i, a) => a.push(val))
If arr is not an array but an array-like, it will turn it into an array and thereby allow you to forEach over it. E.g.:
[...document.getElementsByTagName('p')].forEach(p => console.log(p))
Related
This question already has answers here:
Does .sort function change original array?
(6 answers)
Why A and B are equal after sort()?
(3 answers)
How can you sort an array without mutating the original array?
(11 answers)
Closed 1 year ago.
I came across something strange. Here two variables which store two differents results:
const membersSortedByCurrentStageTotalPoints = teamMembers.sort((a, b) => compareRanking(a,b,currentIndex));
const membersSortedByRankingType = teamMembers.sort((a, b) => compare(a, b, "points"))
But when I'm using the variable membersSortedByCurrentStageTotalPoints I get the results of the variable membersSortedByRankingType.
Anyone would know why ?
From the MDN documentation for sort:
Return value
The sorted array. Note that the array is sorted in place, and no copy
is made.
The two variables both have the same value: A reference to the same array.
This question already has answers here:
How to map more than one property from an array of objects [duplicate]
(7 answers)
Closed 1 year ago.
How can I take (in JS) all the values inside this nested object except for the last two elements (scenario and total). here an image of the object I have:
I need an array equal to this one, but without "scenario" and "total" in the 3 nested objects inside.
Use map function
array.map(item => {
delete item.scenario;
delete item.total;
return item;
});
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());
This question already has answers here:
How to flatten a List?
(6 answers)
Closed 2 years ago.
This is js code of doing it!
nums = [].concat(...digitBuckets);
how can i implement it in dart?
nums=[].addAll(...digitBucketsd);//facing problem here and confused
The spread operator is designed to insert array elements into another array or to map its elements to function arguments.
The mistake is that: elements of array are used as arguments of concat function, but concat function requires array as argument but not its elements as arguments:
replace
nums = [].concat(...digitBuckets);
nums = [].addAll(...digitBucketsd);
with
nums = [].concat(digitBuckets);
nums = [].addAll(digitBucketsd);
or with spread
nums = [...digitBuckets];
nums = [...digitBucketsd];
also digitBucketsd is present in question instead of digitBuckets
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"));