Array
/Object
prototype method JS-D008119 let positive = 0;
120 let negative = 0;
121
122 sentiments_list.map((sentiment) => {123 if (sentiment.sentiment >= 50) {124 positive += 1;125 } else {126 negative += 1;127 }128 });129
130 return folderNameV === folderName ? (
131 <div className="px-6 mx-auto max-w-7xl">
114 let positive = 0;
115 let negative = 0;
116
117 sentiments_list.map((sentiment) => {118 if (sentiment.sentiment >= 50) {119 positive += 1;120 } else {121 negative += 1;122 }123 });124
125 return (
126 <div className="px-6 mx-auto max-w-7xl">
Many built-in functions defined on prototypes for Object
and Array
are pure, and return modified versions of their inputs.
If the return values from these functions aren't used, the function call is essentially a no-op and might as well be removed.
// These calls do not modify the array, instead they
// return new arrays with the desired properties.
xs.map(x => x.prop)
xs.filter(x => x.prop === 'value')
xs.concat(ys)
xs.reduce((x, y) => (x.value + y.value))
Perhaps, you're using map
to iterate over an array and induce some side-effect, like logging to the console as shown here:
xs.map((x, i) => console.log(`element #${i}:`, x))
This use of map
is however misleading.
The map
/filter
/concat
methods should only ever be used to produce new arrays that are used elsewhere.
Instead, you should use the forEach
method:
xs.forEach((x, i) => console.log(`element #${i}:`, x))
const characters = [
{ name: 'Paul Atreides', age: 15 },
{ name: 'Kaladin Stormblessed', age: 19 },
{ name: 'Miss Kobayashi', age: 25 },
{ name: 'Eren Yeager', age: 14 },
{ name: 'Illidan Stormrage', age: 3000 }
]
characters.map(character => character.name);
// characters array is not modified by the call to `map`.
console.log(characters)
const characters = [
{ name: 'Paul Atreides', age: 15 },
{ name: 'Kaladin Stormblessed', age: 19 },
{ name: 'Miss Kobayashi', age: 25 },
{ name: 'Eren Yeager', age: 14 },
{ name: 'Illidan Stormrage', age: 3000 }
]
// array returned by call to `map` is now stored.
const characterNames = characters.map(character=> character.name);
console.log(characterNames)
// [ 'Paul Atreides', 'Kaladin Stormblessed', 'Miss Kobayashi', 'Eren Yeager', 'Illidan Stormrage' ]