/    Sign up×
Community /Pin to ProfileBookmark

Hi,

Let’s say I have an array like this:

var patients=[{city=”London”, score=172},
{city=”London”, score=178},
{city=”Rome”, score=158},
{city=”Paris”, score=17}]

How can i find which city is most and least repeated in an array ?

#javascript

to post a comment
Full-stack Developer

2 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumMar 30.2020 — Not shure what your intention is: Sum up the scores for each city and sort by the result? Or simply count how often each city occurs and sort by that number?
Copy linkTweet thisAlerts:
@SempervivumMar 30.2020 — For the latter try this javascript:
const patients = [
{ city: "London", score: 172 },
{ city: "London", score: 178 },
{ city: "Rome", score: 158 },
{ city: "Paris", score: 17 },
{ city: "Paris", score: 20 },
{ city: "Paris", score: 25 }
];
let result = {};
patients.forEach((item, idx) => {
if (!result[item.city]) {
result[item.city] = 1;
} else {
result[item.city]++;
}
});
let result2 = [];
for (city in result) {
result2.push({ city: city, nr: result[city] });
}
result2.sort((a, b) => a.nr - b.nr);
console.log(result);
console.log(result2);
×

Success!

Help @albionshalaa spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.27,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...