Conversations on the encounter's authenticity still abound.
Chris Ferdinandi turns the heat down low and lets the sauce reduce while we take a look at how to add spice to our source with a sprinkling of Array.reduce(). Just a little ingenuity with the humblest of functions.
Of all the modern array methods, the one I had the hardest time wrapping my head around was Array.reduce()
.
On the surface, it seems like a simple, boring method that doesn’t do much. But below its humble exterior, Array.reduce()
is actually a powerful, flexible addition to your developer toolkit.
Today, we’re going to look at some cool things you can do with Array.reduce()
.
Array.reduce()
worksMost of the modern array methods return a new array. The Array.reduce()
method is a bit more flexible. It can return anything. Its purpose is to take an array and condense its content into a single value.
That value can be a number, a string, or even an object or new array. That’s the part that’s always tripped me up – I didn’t realize just how flexible it is!
The Array.reduce()
accepts two arguments: a callback method to run against each item in the array, and a starting value.
The callback also accepts two arguments: the accumulator
, which is the current combined value, and the current
item in the loop. Whatever you return is used as the accumulator for the next item in the loop. On the very first loop, that starting value is used instead.
var myNewArray = [].reduce(function (accumulator, current) {
return accumulator;
}, starting);
Let’s look at some examples to make this all tangible.
Let’s say you had an array of numbers that you wanted to add together. Using Array.forEach()
, you might do something like this:
var total = 0;
[1, 2, 3].forEach(function (num) {
total += num;
});
This is the cliche example for using Array.reduce()
. I find the word accumulator confusing, so in this example, I’m calling it sum
, because that’s what it is.
var total = [1, 2, 3].reduce(function (sum, current) {
return sum + current;
}, 0);
Here, we pass in 0
as our starting value.
In the callback, we add the current value to the sum
, which has our starting value of 0
on the first loop, then 1
(the starting value of 0
plus the item value of 1
), then 3
(the sum value of 1
plus the item value of 2
), and so on.
Array.map()
and Array.filter()
into a single stepImagine you had an array of wizards
at Hogwarts.
var wizards = [
{
name: 'Harry Potter',
house: 'Gryfindor'
},
{
name: 'Cedric Diggory',
house: 'Hufflepuff'
},
{
name: 'Tonks',
house: 'Hufflepuff'
},
{
name: 'Ronald Weasley',
house: 'Gryfindor'
},
{
name: 'Hermione Granger',
house: 'Gryfindor'
}
];
You want to create a new array that contains just the names of wizards who are in Hufflepuff. One way you could do that is by using the Array.filter()
method to get back just wizards
whose house
property is Hufflepuff
. Then, you’d use the Array.map()
method to create a new array containing just the name
property for the remaining wizards.
// Get the names of the wizards in Hufflepuff
var hufflepuff = wizards.filter(function (wizard) {
return wizard.house === 'Hufflepuff';
}).map(function (wizard) {
return wizard.name;
});
With the Array.reduce()
method, we can get the same array in a single pass, improving our performance. You pass in an empty array ([]
) as the starting value. On each pass, you check to see if the wizard.house
is Hufflepuff
. If it is, you push it to the newArr
(our accumulator
in this example). If not, you do nothing.
Either way, you return the newArr
to become the accumulator
on the next pass.
// Get the names of the wizards in Hufflepuff
var hufflepuff = wizards.reduce(function (newArr, wizard) {
if (wizard.house === 'Hufflepuff') {
newArr.push(wizard.name);
}
return newArr;
}, []);
What if, instead of creating an array of names, we wanted to create an unordered list of wizards in Hufflepuff? Instead of passing an empty array into Array.reduce()
as our starting value, we’ll pass in an empty string (''
) and call it html
.
If the wizard.house
equals Hufflepuff
, we’ll concatenate our html
string with the wizard.name
wrapped in an opening and closing list item (li
). Then, we’ll return the html
to become the accumulator
on the next loop.
// Create a list of wizards in Hufflepuff
var hufflepuffList = wizards.reduce(function (html, wizard) {
if (wizard.house === 'Hufflepuff') {
html += '<li>' + wizard.name + '</li>';
}
return html;
}, '');
Add an opening and closing unordered list element before and after Array.reduce()
, and you’re ready to inject your markup string into the DOM.
// Create a list of wizards in Hufflepuff
var hufflepuffList = '<ul>' + wizards.reduce(function (html, wizard) {
if (wizard.house === 'Hufflepuff') {
html += '<li>' + wizard.name + '</li>';
}
return html;
}, '') + '</ul>';
The lodash library has a groupBy()
method takes a collection of items as an array and groups them together into an object based on some criteria.
Let’s say you want an array of numbers.
If you wanted to group all of the items in numbers
together based on their integer value, you would do this with lodash.
var numbers = [6.1, 4.2, 6.3];
// returns {'4': [4.2], '6': [6.1, 6.3]}
_.groupBy(numbers, Math.floor);
If you had an array of words, and you wanted to group the items in words
by their length, you would do this.
var words = ['one', 'two', 'three'];
// returns {'3': ['one', 'two'], '5': ['three']}
_.groupBy(words, 'length');
groupBy()
function with Array.reduce()
You can recreate that same functionality using the Array.reduce()
method.
We’ll create a helper function, groupBy()
, that accepts the array and criteria to sort by as arguments. Inside groupBy()
, we’ll run Array.reduce()
on our array, passing in an empty object ({}
) as our starting point, and return the result.
var groupBy = function (arr, criteria) {
return arr.reduce(function (obj, item) {
// Some code will go here...
}, {});
};
Inside the Array.reduce()
callback function, we’ll check to see if the criteria
is a function, or a property of the item
. Then we’ll get its value from the current item
.
If there’s no property in the obj
with that value yet, we’ll create it and assign an empty array as its value. Finally, we’ll push the item
to that key
, and return the object as the accumulator
for the next loop.
var groupBy = function (arr, criteria) {
return arr.reduce(function (obj, item) {
// Check if the criteria is a function to run on the item or a property of it
var key = typeof criteria === 'function' ? criteria(item) : item[criteria];
// If the key doesn't exist yet, create it
if (!obj.hasOwnProperty(key)) {
obj[key] = [];
}
// Push the value to the object
obj[key].push(item);
// Return the object to the next item in the loop
return obj;
}, {});
};
Here’s a demo of the completed helper function.
Special thanks to Tom Bremer for helping me make some improvements to this one. You can find this helper function and more like it on the Vanilla JS Toolkit.
Remember our array of wizards?
var wizards = [
{
name: 'Harry Potter',
house: 'Gryfindor'
},
{
name: 'Cedric Diggory',
house: 'Hufflepuff'
},
{
name: 'Tonks',
house: 'Hufflepuff'
},
{
name: 'Ronald Weasley',
house: 'Gryfindor'
},
{
name: 'Hermione Granger',
house: 'Gryfindor'
}
];
What if you had another data set, an object of house points each wizard has earned.
var points = {
HarryPotter: 500,
CedricDiggory: 750,
RonaldWeasley: 100,
HermioneGranger: 1270
};
Imagine you wanted to combine both sets of data into a single array, with the number of points
added to each wizard’s data in the wizards
array. How would you do it?
The Array.reduce()
method is perfect for this!
var wizardsWithPoints = wizards.reduce(function (arr, wizard) {
// Get the key for the points object by removing spaces from the wizard's name
var key = wizard.name.replace(' ', '');
// If the wizard has points, add them
// Otherwise, set them to 0
if (points[key]) {
wizard.points = points[key];
} else {
wizard.points = 0;
}
// Push the wizard object to the new array
arr.push(wizard);
// Return the array
return arr;
}, []);
Here’s a demo combining data from two sources into an array.
What if you instead wanted to combine the two data sources into an object, where each wizard’s name was the key, and their house and points were properties? Again, the Array.reduce()
method is perfect for this.
var wizardsAsAnObject = wizards.reduce(function (obj, wizard) {
// Get the key for the points object by removing spaces from the wizard's name
var key = wizard.name.replace(' ', '');
// If the wizard has points, add them
// Otherwise, set them to 0
if (points[key]) {
wizard.points = points[key];
} else {
wizard.points = 0;
}
// Remove the name property
delete wizard.name;
// Add wizard data to the new object
obj[key] = wizard;
// Return the array
return obj;
}, {});
Here’s a demo combining two data sets into an object.
Array.reduce()
more?The Array.reduce()
method has gone from being something I thought was pointless to my favorite JavaScript method. So, should you use it? And when?
The Array.reduce()
method has fantastic browser support. It works in all modern browsers, and IE9 and above. It’s been supported in mobile browsers for a long time, too. If you need to go back even further than that, you can add a polyfill to push support back to IE6.
The biggest complaint you can make about Array.reduce()
is that it’s confusing for people who have never encountered it before. Combining Array.filter()
with Array.map()
is slower to run and involves extra steps, but it’s easier to read. It’s obvious from the names of the methods what they’re supposed to be doing.
That said, there are times where Array.reduce()
makes things that would be complicated more simple rather than more complicated. The groupBy()
helper function is a good example.
Ultimately, this is another tool to add to your toolkit. A tool that, if used right, can give you super powers.
Chris Ferdinandi helps people learn vanilla JavaScript. He believes there’s a simpler, more resilient way to make things for the web.
Chris is the author of the Vanilla JS Pocket Guide series, creator of the Vanilla JS Academy training program, and host of the Vanilla JS Podcast. His developer tips newsletter is read by thousands of developers each weekday.
He’s taught developers at organizations like Chobani and the Boston Globe, and his JavaScript plugins have been used used by Apple and Harvard Business School. Chris Coyier, the founder of CSS-Tricks and CodePen, has described his writing as “infinitely quote-worthy.”
Chris loves pirates, puppies, and Pixar movies, and lives near horse farms in rural Massachusetts. He runs Go Make Things with Bailey Puppy, a lab-mix from Tennessee.
In 2018, industry research firm Gartner made a rather disheartening prediction: Some 85 percent of AI projects are doomed to failure. Wow. That’s a lot. Keep that number at the back of your mind. Now consider how many questions an organization must answer when it comes to this kind of project implementation: Do we have […]
The post Five Steps to Take to Give Your AI Project a Fighting Chance at Success appeared first on DevelopIntelligence.
Social media marketing is a strategy employed by many companies. One of the biggest complaints I hear from businesses is that they're not having much success on social media. The thing is that certain social media marketing mistakes can cause brands to fail. I'll be addressing several issues that may be impacting your social media efforts in this article.
Are you making any of the following mistakes?
Five Social Media Marketing Mistakes You Must Avoid
WIRED's editor-in-chief, Nicholas Thompson, on the five things he'll be watching for during Facebook C.E.O. Mark Zuckerberg's testimony before Congress.
Five-foot-tall, 400-pound robots are on a mission to take a bite out of crime. The path there, though, is fraught with ethical pitfalls.
Five years ago, as its voice recognition tech took off, Google realized it would have to double its server space to handle even three minutes of speech from every Android user. Even Google couldn't afford that. So Urs Hözle and his team built a super chip to parse all that data more efficiently.
Five female engineers discuss the sexism of the tech industry and why greater diversity and inclusion makes better products for everyone.
A five-year-old Indian boy has become a millionaire overnight after winning a lottery at a national bond draw here.
A five-year old boy here survived a 40-feet fall from a multi-storeyed building with minor scratches.
Five years ago, the AP court had ordered a cut in prices of cottonseeds from Rs 1,600 to Rs 650 per bag. Other states had followed suit
Five people were killed and nine critically injured in an explosion at Bajrapara in Jalpaiguri district in north Bengal.
Five days after the Short Street shootout, Kolkata witnessed yet another incident in Lake Town Friday.
I have been hearing a lot of marketers talk about social commerce, which is exactly what it sounds like: using social media networks to help sell products online. This may sound like a relatively new idea, but when you take a deeper look, social commerce was actually introduced by Yahoo in late 2005. At the time, things like product reviews and sharing wish lists were cutting edge, but that was one of the early examples of combining social networking with online commerce. Technology has since evolved, but the idea remains the same. To understand how to succeed in social commerce, here are five tips for using social networks to sell products online.
complete article
Every marketer today wants to make their brand presence felt. That is the reason why social media is being leveraged on a big scale. Whether one owns an established business or a startup, social media marketing is something that everyone is using to reach and communicate with the customers. Doesn’t it make sense to be in a place where the crowd is? One often comes across some social media marketing activities that fail. While, on the other hand, some Facebook and Twitter pages become popular than the others. Many times, marketers observe that their competitors are doing better than them in social media marketing!
Everybody does make mistakes. How can social media marketers be any different? But the fact is, making too many mistakes can see the followers dwindle and their count drop. Indeed, it does affect the revenue of a business. As with all mistakes, the first step is understanding and becoming aware of them. It then becomes easier to avoid them in the future.
complete article
Keeping tabs on the rich, famous, and just-plain-cool is nothing new, of course. But social media can take that fixation to a pretty dark place. The feeling is common enough that some doctors are calling it social media anxiety disorder (SMAD) – although what most kids have is more like FOMO ... on steroids. While it is tough to see your kid in despair, there is a good solution that doesn't require an all-out social media ban: Just help your kid clean up their feed.
Self-comparison is a natural part of the tween and teen years. And for most kids, so is social media. While there are plenty of good things kids get out of their online connections, sometimes the combo can lead to a negative feedback loop that gnaws away at them.
complete article
RSS offers an efficient way to stay in the know, but the right newsreader can make a big difference. Here are five outstanding Android apps that should do the trick.
complete article
If you are a news junkie, you probably depend on various and sundry RSS feeds—so you most likely need a handy app to curate them into a single, easy-to-use location. Fortunately, plenty of Android apps are available to handle all your RSS needs.
complete article
RSS offers an efficient way to stay in the know, but the right newsreader can make a big difference. Here are five outstanding Android apps that should do the trick.
complete article
If you are a news junkie, you probably depend on various and sundry RSS feeds—so you most likely need a handy app to curate them into a single, easy-to-use location. Fortunately, plenty of Android apps are available to handle all your RSS needs.
What is RSS?
For those who are new to RSS, here's a quick overview. RSS stands for rich site summary (or really simple syndication). It enables sites to publish frequently updated information in a format that is easy to consume (by both apps and humans). The format of RSS tends to be a title and a one-sentence or one-paragraph blurb. Readers can click on the title, which will take them to the original piece.
Different apps offer different features for RSS feeds. I have found five apps in the Google Play Store that I believe represent the best features and the most user-friendly interfaces.
complete article
Online Resource
Five prominent labour activists have returned to their homes more than a year after they were arrested in coordinated raids in the southern Chinese city of Shenzhen, according to people close to them and a Hong Kong-based rights group.
A trooper stopping a car with a suspected "impaired driver" on a U.S. highway on Monday was bemused to find a 5-year-old in the driver's seat, the Utah Highway Patrol tweeted.
Bollywood actress Sara Ali Khan has captured the hearts of the audience with her charming personality and acting prowess. Apart from it, her sartorial picks has also left us stunned. Be it events or festivals, the diva has been giving
Here is yet another report which have once again proven that cleanliness is directly related to your sexuality. A leading psychologist Donna Dawson says, "If someone wants to know how some other person performs between the sheets, he/she should look how
There have been 73 reported cases in New York where children are experiencing symptoms similar to Kawasaki disease and toxic shock-like syndrome possibly due to Covid-19.
All the fresh cases are from Khajpura area of Patna and their infection trail is being ascertained by state health officials.
Five days after three doctors working in the Covid hospital of BPS Khanpur Medical College, Sonipat, were found positive of coronavirus, 11 junior doctors who were their contacts have been sent in 14-day quarantine.
Five migrant workers who returned to their homes in Palamu from Chhattisgarh in an autorickshaw on May 1 tested positive for Covid-19 on Thursday, taking the state’s tally of coronavirus cases to 132. Of these, 89 are active cases while 41 have recovered and two have died during treatment.
Five people were discharged from the All India Institute of Medical Sciences (AIIMS) in Raipur in Chhattisgarh on Saturday after recovering from the novel coronavirus infection, health officials said. Those discharged include two women and a five-year-old boy, an official informed. So far 43 people have been discharged while the number of active cases in the state is 16, he added. "Two women and a boy from Kabirdham, two men from Durg and Surajpur were discharged after two consecutive tests were negative for the infection. They will be kept in a quarantine centre as a precaution before they are allowed to go home," a public relations officer of AIIMS Raipur told PTI. Chhattisgarh COVID-19 figures are as follows: Positive cases 59; New cases nil; Deaths nil; Discharged 43; Active cases 16; People tested so far 23,629.
Five persons were killed in a clash between two groups at Moti Hamirpar village in Kutch district of Gujarat on Saturday afternoon, police said. A group of people wielding sharp weapons attacked another group on suspicion that they were informing police about the hooch trade in nearby areas, said an official. Liquor production and sale are prohibited in Gujarat. Four persons were killed on the spot while another died at a hospital at Rapar. Kutch-East Superintendent of Police Parikshita Rathod said teams from nearby police stations and the local crime branch was deployed in the village to maintain peace. The deceased were identified as Jesang Rajput, Amra Rajput, Petha Bhavan Rajput, Vela Pecha and and Akhabhai. Further probe was on, the SP said.
Five special trains will start journey from three states on Saturday to bring back 5,000 stranded Odia people, a day after the Supreme Court allowed the return of migrants to Odisha, officials said here. The Supreme Court on Friday stayed an interim order of the Orissa High Court which had asked the state government to ensure that only those tested negative for COVID-19 were allowed to return to Odisha. Three trains will come from Gujarat and one each from Maharashtra and Tamil Nadu, the officials said, adding that about 5,000 people will return to Odisha by these five trains. A senior East Coast Railways official said one of the five trains has already left from Surat for Odisha's Ganjam district. Two trains will leave from Ahmedabad in Gujarat for Khurda Road in Odisha, one train from Panvel station in Mumbai will start the journey to Odisha's Titlagarh in Bolangir district and another will leave from Chennai for Jagannathpur in Ganjam district, the official said. Meanwhile, Odisha .
Five people were arrested for allegedly conducting congregational prayers at a mosque here in violationofthe COVID-19 lockdown norms. A case was registered against five people for conducting evening prayers on Friday, police said. We received information that prayers were being conducted in the mosque, they said adding they were held at Eriyad Masjidul Bilal mosque here. On Friday, four people, including the president of a local temple trust, were arrested for allegedly conducting a religious recitation in a temple here in violation of lockdown restrictions. Though lockdown conditions have been eased in accordance with the Centre's guidelines, public gatherings, including functions, weddings, political events and religious gatherings were not allowed.
Five Bihar Military Police (BMP) personnel have tested positive for novel coronavirus, taking the total number of COVID-19 cases in the state to 579, a top health official said. All the fresh cases are from Khajpura area of Patna and their infection trail is being ascertained, Health Department Principal Secretary Sanjay Kumar said. Kumar tweeted late on Friday evening, "5 more COVID-19 positive cases in Bihar taking the total to 579. 5-males 30,36,50,52 and 57 years from Khajpura Patna. All are BMP jawans. We are ascertaining their further infection trail." Coronavirus has spread to 36 of the 38 districts in the state, officials said. Five patients have died so far and 307 people are still afflicted with the disease, while 267 have recovered, they said. One death each was reported in Rohtas, Munger, Vaishali, East Champaran and Sitamarhi districts. All the deceased were males and barring one, every one of them was below 60 years of age and with pre-existing medical conditions, the ...
Five people, who had travelled from Rajasthan to Silchar, tested positive for COVID-19 on Friday, taking the total number of cases in Assam to 58, Health Minister Himanta Biswa Sarma said. Of the total 58 cases, 23 are active, he said. "There are two more COVID-19 patients who travelled in the bus which ferried people from Rajasthan. They are from Cachar district," the minister tweeted. Three other persons tested positive earlier in the day, while four others tested positive on Thursday and another on Wednesday, taking the total number of cases related to this group, who came from Ajmer to 10. The patients have been admitted to Silchar Medical College Hospital. A bus carrying 45 passengers and crew, arrived at Silchar on Wednesday, after being given permission by the Ajmer Deputy Commissioner. Of them 10 have tested positive so far. As the passengers had gone home briefly after screening, several areas in four villages of Cachar district has been declared as containment zones, he ...
Five thousand lets have claimed £10,000 each from the fund in Cornwall (pictured, St Ives), which was set up to help minor firms survive the coronavirus lockdown.
All five of the most unique homes for sale on the property website were picked by the Rightmove team for their stand out features.
There are steps you take to help sell your home, such as replacing old fixtures and fittings and jazzing up your garden.
Five of this autumn's most popular interior design trends have been revealed by renovation website Houzz - it includes bold wallpaper prints in the loo.
From whether payment holidays will affect your credit file to what to do if you're struggling to pay your bills, debt charity StepChange answers five of the most common questions they've received.
Negative reviews can make or break a business with 94% of people saying an online review has convinced them to avoid a business altogether.
Internet providers are ripping off up to five million customers with a shoddy snail's pace service - when they should be paying less for a faster broadband.
Televisions were the item that varied the most in price via retailer with the average price difference of £364.77, according to the price comparison website, Idealo.
If you are someone who is looking to start the new year by paying off more of their debt, This is Money and its personal finance experts are here to help.
Have you ever checked your credit report? If the answer is no, the likelihood is: someone else has. We reveal five top tips for those who have never cast an eye on their financial CV.