Just a note in addition to the other answers.
If an initial value is supplied to reduce then sometimes its type must be specified, viz:-
Copya.reduce(fn, [])
may have to be
Copya.reduce<string[]>(fn, [])
or
Copya.reduce(fn, <string[]>[])
Answer from Quentin 2 on Stack OverflowMDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › reduce
Array.prototype.reduce() - JavaScript | MDN
Thrown if the array contains no elements and initialValue is not provided. The reduce() method is an iterative method. It runs a "reducer" callback function over all elements in the array, in ascending-index order, and accumulates them into a single value. Every time, the return value of callbackFn ...
Top answer 1 of 6
192
Just a note in addition to the other answers.
If an initial value is supplied to reduce then sometimes its type must be specified, viz:-
Copya.reduce(fn, [])
may have to be
Copya.reduce<string[]>(fn, [])
or
Copya.reduce(fn, <string[]>[])
2 of 6
99
It's actually the JavaScript array reduce function rather than being something specific to TypeScript.
As described in the docs: Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.
Here's an example which sums up the values of an array:
Copylet total = [0, 1, 2, 3].reduce((accumulator, currentValue) => accumulator + currentValue);
console.log(total);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
The snippet should produce 6.
How do I type reduce when Im reducing an array to count elements?
reduce>(...) Unrelated but personally when I end up reducing an array that I mapped before, I just remove then map and do it all in the reduce. This makes it so we don't iterate the whole array twice. Sometimes it's not a big optimization but it can be with medium to large arrays. More on reddit.com
How to reduce array of objects to array
Greetings, Say for example i dont wish to use a for loop or forEach, I also dont wish to map and then do another pass to clear undefined values. how would I say convert an array of objects into different array, want this… More on forum.freecodecamp.org
Typescript and Array.reduce()
Was toying with the following code ... the array was composed of number) or the concatenation (if the array was composed of strings) Typescript doesnt seem to like Array.reduce method.... More on sitepoint.com
JavaScript Reduce - A Complete Guide to the Only JS Array Function You Really Need
While I understand the title of the article is intentionally a bit provocative, it gives some interesting insight into what reduce can be used for, but it also mythologizes it a fair bit. There are few things reduce does that could not be made simpler, faster and more readable with a variable and a regular for-loop, or the appropriate specialized method. Interesting rundown of what reduce COULD be used for, yes, but if a member of my team started writing const doubledNumbers = numbers.reduce((result, num) => { result.push(num * 2); return result; }, []); instead of just using .map(), I would have strong words to say. Not to mention how annoying reduce is in TypeScript, where it often fails automatic type resolution spectacularly. More on reddit.com
Videos
Función REDUCE con Array de Objetos | JavaScript - YouTube
The magic of the reduce method in javascript/typescript: simplifying ...
12:11
Typescript, Array reduce examples - YouTube
10:51
Master JavaScript Array Reduce Method In 10 Minutes - YouTube
03:27
How the JavaScript Array Reduce Method Works - YouTube
Typescript, Array reduce examples
Reddit
reddit.com › r/typescript › how do i type reduce when im reducing an array to count elements?
r/typescript on Reddit: How do I type reduce when Im reducing an array to count elements?
October 11, 2022 -
interface MoodTableType {
[key: string]: number
}
useEffect(() => {
const moodTableData = data?.map((item) => item.feelBefore); // [ "a","b","a"]
const graphData = moodTableData.reduce((total, value) => { //{a:2,b:1}
total[value] = (total[value] || 0) + 1;
return total;
}, {})
console.log("moodTableData", moodTableData, graphData);
}, [data])I get error at value in total[value] that says
"message": "Element implicitly has an 'any' type because index expression is not of type 'number'.", I know im supposed to use as keyOf somewhere but im a bit lost. Not sure if my interface is right either
Top answer 1 of 5
4
reduce>(...) Unrelated but personally when I end up reducing an array that I mapped before, I just remove then map and do it all in the reduce. This makes it so we don't iterate the whole array twice. Sometimes it's not a big optimization but it can be with medium to large arrays.
2 of 5
4
The .reduce method takes a generic. So it would be: const graphData = moodTableData.reduce((total, value) => { //{a:2,b:1} total[value] = (total[value] || 0) + 1; return total; }, {}) If you want stricter types you could do something like this: const data = [{feelBefore:'a'},{feelBefore:'b'},{feelBefore:'a'}] as const type TData = typeof data[number] type TDataKey = TData[keyof TData] type MoodTableType = Record const moodTableData = data?.map((item) => item.feelBefore); // [ "a","b","a"] const graphData = moodTableData.reduce((total, value) => { //{a:2,b:1} total[value] = (total[value] || 0) + 1; return total; }, {} as MoodTableType) Then your type would be: type MoodTableType = { a: number; b: number; } Only works if the data is known at compile time of course :)
freeCodeCamp
forum.freecodecamp.org › javascript
How to reduce array of objects to array
June 12, 2022 - Greetings, Say for example i dont wish to use a for loop or forEach, I also dont wish to map and then do another pass to clear undefined values. how would I say convert an array of objects into different array, want this input: [ {a:1}, {name: 'Jane'}, {}, {b:2}, {name: 'Smith'}, {name: 'Fatima'}, ] to output e.g. : ['Jane', 'Smith', 'Fatima'] Can it be done using reduce?
TutorialsPoint
tutorialspoint.com › typescript › typescript_array_reduce.htm
TypeScript - Array reduce()
reduce() method applies a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value. Returns the reduced single value of the array.
Medium
j5cookie.medium.com › async-array-reduce-in-typescript-e116ba1f3578
Async array.reduce() in Typescript
April 9, 2022 - const ourFavoriteFamilyArray = [ ["Homer", "Homer Simpson"], ["Marge", "Marge Simpson"], ["Lisa", "Lisa Simpson"], ["Bart", "Bart Simpson"], ["Maggie", "Maggie Simpson"] ];const pretendThisIsAsync = (familyMember) => { return Promise.resolve(familyMember[1]); };const ourFavoriteFamilyMapPromise = ourFavoriteFamilyArray.reduce( (familyAccumulatorPromise, familyMember) => { return familyAccumulatorPromise.then((family) => { return pretendThisIsAsync(familyMember) .then((processedFamilyMember) => { family[familyMember[0]] = processedFamilyMember; return family; }); }); }, Promise.resolve({}));ourFavoriteFamilyMapPromise.then((family) => { console.log("2. Promise Reduce", family); }); That’s asynchronous, but is it async? We want this cleaner, right? We want to be able to type this with Typescript without going insane, right?
Reddit
reddit.com › r/javascript › javascript reduce - a complete guide to the only js array function you really need
r/javascript on Reddit: JavaScript Reduce - A Complete Guide to the Only JS Array Function You Really Need
January 11, 2024 - It's a good rule of thumb IMHO, when mutating and returning the same thing in reduce there is probably a simpler way. Like you said, map in this case. ... I was thinking this exact same thing. The original code is horrible using Array.push() like that.
Reddit
reddit.com › r/reactjs › [deleted by user]
Array.reduce() feels like a cheat code/superpower if you ...
November 1, 2022 - You have access to the entire input collection, but you don't have access to a running accumulator. reduce gives you that. More replies More replies More replies ... So true. My rule of thumb for using it is when I need a new type like an object or number from the array.
Kennethlange
kennethlange.com › reduce-in-typescript-examples
8 Examples of Using Reduce in TypeScript – Kenneth Lange
When we have an array of objects, reduce is an easy way to identify the smallest element. For example, if we want to find the blog post with the least number of likes, we can do it like this: const posts = [ {id: 1, title: 'Clean TypeScript', category: 'TypeScript', likes: 91}, {id: 2, title: ...
W3Schools
w3schools.com › jsref › jsref_reduce.asp
W3Schools.com
The reduce() method executes a reducer function for array element.
DEV Community
dev.to › dvddpl › what-s-wrong-with-array-reduce-21mm
What s wrong with Array.reduce ? - DEV Community
March 24, 2021 - const max = (numbers) => numbers.reduce((max, number) => number > max ? number : max); I will never be convinced that a for loop is more readable than that (and map and filter aren't options for this type of computation) ... Currently interested in TypeScript, Vue, Kotlin and Python.
Kennethlange
kennethlange.com › reduce-in-typescript
Reduce in TypeScript – Kenneth Lange
An initial value of the variable that will eventually be returned as the result of the reduce function. The initial value is 0 in the sum example above. A function that is called for each element in the array, so in the sum example above it would be called three times.