Return only the number of paired values in array javascriptPerformance of key lookup in JavaScript objectValidate decimal numbers in JavaScript - IsNumeric()Which “href” value should I use for JavaScript links, “#” or “javascript:void(0)”?How do I check if an array includes an object in JavaScript?How to insert an item into an array at a specific index (JavaScript)?How can I get query string values in JavaScript?How do I empty an array in JavaScript?Get all unique values in a JavaScript array (remove duplicates)Loop through an array in JavaScriptHow do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?
How invisible hand adjusts stock prices if company is listed on multiple exchanges, under multiple currencies, and one of the currencies plunges?
Did the Byzantines ever attempt to move their capital to Rome?
Why does PAUSE key have a long make code and no break code?
Contour plot of a sequence of spheres with increasing radius
What is the purpose of the rotating plate in front of the lock?
How can faith be maintained in a world of living gods?
Why would an AC motor heavily shake when driven with certain frequencies?
Do aarakocra have arms as well as wings?
Python implementation of atoi
How strong is aircraft-grade spruce?
Why did Tony's Arc Reactor do this?
Why does low tire pressure decrease fuel economy?
Why are UK MPs allowed to abstain (but it counts as a no)?
Why can't some airports handle heavy aircraft while others do it easily (same runway length)?
Is mountain bike good for long distances?
Word for something that used to be popular but not anymore
How to run NPCs with complicated mechanics?
What is the delta-v required to get a mass in Earth orbit into the sun using a SINGLE transfer?
antimatter annihilation in stars
How would two worlds first establish an exchange rate between their currencies
Friend is very nitpicky about side comments I don't intend to be taken too seriously
Why is infinite intersection "towards infinity" an empty set?
Owner keeps cutting corners and poaching workers for his other company
What precisely does the commonly reported network hash rate refer to?
Return only the number of paired values in array javascript
Performance of key lookup in JavaScript objectValidate decimal numbers in JavaScript - IsNumeric()Which “href” value should I use for JavaScript links, “#” or “javascript:void(0)”?How do I check if an array includes an object in JavaScript?How to insert an item into an array at a specific index (JavaScript)?How can I get query string values in JavaScript?How do I empty an array in JavaScript?Get all unique values in a JavaScript array (remove duplicates)Loop through an array in JavaScriptHow do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
My purpose is to display the number of paired values in the array.
for instance I have this array :[10,10,10,10,20,20,20,30,50]
I would like to display 3 because we have 3 pairs of number.
Any help will be greatly appreciated.
function pairNumber(arr)
var sorted_arr = arr.sort();
var i;
var results = [];
for (i = 0; i < sorted_arr.length; i++)
if (sorted_arr[i + 1] == sorted_arr[i])
results.push(sorted_arr[i]);
return results.length;
console.log(pairNumber([10, 10, 10, 10, 20, 20, 20, 30, 50]))
javascript
add a comment |
My purpose is to display the number of paired values in the array.
for instance I have this array :[10,10,10,10,20,20,20,30,50]
I would like to display 3 because we have 3 pairs of number.
Any help will be greatly appreciated.
function pairNumber(arr)
var sorted_arr = arr.sort();
var i;
var results = [];
for (i = 0; i < sorted_arr.length; i++)
if (sorted_arr[i + 1] == sorted_arr[i])
results.push(sorted_arr[i]);
return results.length;
console.log(pairNumber([10, 10, 10, 10, 20, 20, 20, 30, 50]))
javascript
add a comment |
My purpose is to display the number of paired values in the array.
for instance I have this array :[10,10,10,10,20,20,20,30,50]
I would like to display 3 because we have 3 pairs of number.
Any help will be greatly appreciated.
function pairNumber(arr)
var sorted_arr = arr.sort();
var i;
var results = [];
for (i = 0; i < sorted_arr.length; i++)
if (sorted_arr[i + 1] == sorted_arr[i])
results.push(sorted_arr[i]);
return results.length;
console.log(pairNumber([10, 10, 10, 10, 20, 20, 20, 30, 50]))
javascript
My purpose is to display the number of paired values in the array.
for instance I have this array :[10,10,10,10,20,20,20,30,50]
I would like to display 3 because we have 3 pairs of number.
Any help will be greatly appreciated.
function pairNumber(arr)
var sorted_arr = arr.sort();
var i;
var results = [];
for (i = 0; i < sorted_arr.length; i++)
if (sorted_arr[i + 1] == sorted_arr[i])
results.push(sorted_arr[i]);
return results.length;
console.log(pairNumber([10, 10, 10, 10, 20, 20, 20, 30, 50]))
function pairNumber(arr)
var sorted_arr = arr.sort();
var i;
var results = [];
for (i = 0; i < sorted_arr.length; i++)
if (sorted_arr[i + 1] == sorted_arr[i])
results.push(sorted_arr[i]);
return results.length;
console.log(pairNumber([10, 10, 10, 10, 20, 20, 20, 30, 50]))
function pairNumber(arr)
var sorted_arr = arr.sort();
var i;
var results = [];
for (i = 0; i < sorted_arr.length; i++)
if (sorted_arr[i + 1] == sorted_arr[i])
results.push(sorted_arr[i]);
return results.length;
console.log(pairNumber([10, 10, 10, 10, 20, 20, 20, 30, 50]))
javascript
javascript
edited 8 hours ago
CertainPerformance
130k17 gold badges86 silver badges116 bronze badges
130k17 gold badges86 silver badges116 bronze badges
asked 8 hours ago
DiaslineDiasline
17412 bronze badges
17412 bronze badges
add a comment |
add a comment |
3 Answers
3
active
oldest
votes
Here is another approach using a Set
:
function pairNumbers(arr)
let count = 0;
const set = new Set();
for (let i = 0; i < arr.length; i++)
if (set.has(arr[i]))
count++;
set.delete(arr[i])
else
set.add(arr[i])
return count;
console.log(pairNumbers([10, 10, 10, 10, 20, 20, 20, 30, 50])) // 3
this is a smart solution!
– georg
8 hours ago
@georg thanks for the edit, missed that :)
– Matt Aft
8 hours ago
add a comment |
I'd reduce into an object, counting up the number of occurrences of each number. Then reduce again on the Object.values
of the object to count up the number of pairs, adding Math.floor(count / 2)
to the accumulator on each iteration:
function pairNumber(arr)
const itemCounts = arr.reduce((a, item) =>
a[item] = (a[item] , );
return Object.values(itemCounts)
.reduce((pairsSoFar, count) => pairsSoFar + Math.floor(count / 2), 0);
console.log(pairNumber([10, 10, 10, 10, 20, 20, 20, 30, 50]))
Probably better to avoid .sort
if possible - that increases the computational complexity from O(n)
(minimum) to O(n log n)
.
I wonder if buildingitemCounts
doesn't add the sameO(nlogn)
back? How do objects work under the hood? Hashtables? Balanced trees?
– Vilx-
8 hours ago
For any remotely sane implementation, it'll beO(1)
, luckily: stackoverflow.com/questions/7700987/… . If using an object causes an issue, could use a Map instead
– CertainPerformance
8 hours ago
add a comment |
If I understood the question well then this can be simplified even further by relying on sort initially...
Increment i to the next position after finding the pair and let the for loop increment it once again.
function pairNumber(arr)
var sorted_arr = [...arr].sort(); // disallowing array mutation
let cnt = 0;
for (let i = 0; i < sorted_arr.length; i++)
if (sorted_arr[i + 1] === sorted_arr[i])
cnt++;
i = i + 1;
return cnt;
console.log(pairNumber([10, 10, 10, 10, 10, 20, 20, 20, 20, 30, 30, 50]))
// 5 --> 2 pairs of 10, 2 pairs of 20, 1 pair of 30
console.log(pairNumbers([10, 10, 10, 10, 20, 20, 20, 30, 50]))
// 3 --> 2 pairs of 10 one pair of 20
1
I believesort
will mutate the original array, so a side-effect would be that the array being passed in will be sorted after calling this function.
– Matt Aft
7 hours ago
@MattAft tnx, edited my answer
– Eugene Sunic
7 hours ago
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57837661%2freturn-only-the-number-of-paired-values-in-array-javascript%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
Here is another approach using a Set
:
function pairNumbers(arr)
let count = 0;
const set = new Set();
for (let i = 0; i < arr.length; i++)
if (set.has(arr[i]))
count++;
set.delete(arr[i])
else
set.add(arr[i])
return count;
console.log(pairNumbers([10, 10, 10, 10, 20, 20, 20, 30, 50])) // 3
this is a smart solution!
– georg
8 hours ago
@georg thanks for the edit, missed that :)
– Matt Aft
8 hours ago
add a comment |
Here is another approach using a Set
:
function pairNumbers(arr)
let count = 0;
const set = new Set();
for (let i = 0; i < arr.length; i++)
if (set.has(arr[i]))
count++;
set.delete(arr[i])
else
set.add(arr[i])
return count;
console.log(pairNumbers([10, 10, 10, 10, 20, 20, 20, 30, 50])) // 3
this is a smart solution!
– georg
8 hours ago
@georg thanks for the edit, missed that :)
– Matt Aft
8 hours ago
add a comment |
Here is another approach using a Set
:
function pairNumbers(arr)
let count = 0;
const set = new Set();
for (let i = 0; i < arr.length; i++)
if (set.has(arr[i]))
count++;
set.delete(arr[i])
else
set.add(arr[i])
return count;
console.log(pairNumbers([10, 10, 10, 10, 20, 20, 20, 30, 50])) // 3
Here is another approach using a Set
:
function pairNumbers(arr)
let count = 0;
const set = new Set();
for (let i = 0; i < arr.length; i++)
if (set.has(arr[i]))
count++;
set.delete(arr[i])
else
set.add(arr[i])
return count;
console.log(pairNumbers([10, 10, 10, 10, 20, 20, 20, 30, 50])) // 3
edited 8 hours ago
georg
166k37 gold badges221 silver badges322 bronze badges
166k37 gold badges221 silver badges322 bronze badges
answered 8 hours ago
Matt AftMatt Aft
5,4758 silver badges24 bronze badges
5,4758 silver badges24 bronze badges
this is a smart solution!
– georg
8 hours ago
@georg thanks for the edit, missed that :)
– Matt Aft
8 hours ago
add a comment |
this is a smart solution!
– georg
8 hours ago
@georg thanks for the edit, missed that :)
– Matt Aft
8 hours ago
this is a smart solution!
– georg
8 hours ago
this is a smart solution!
– georg
8 hours ago
@georg thanks for the edit, missed that :)
– Matt Aft
8 hours ago
@georg thanks for the edit, missed that :)
– Matt Aft
8 hours ago
add a comment |
I'd reduce into an object, counting up the number of occurrences of each number. Then reduce again on the Object.values
of the object to count up the number of pairs, adding Math.floor(count / 2)
to the accumulator on each iteration:
function pairNumber(arr)
const itemCounts = arr.reduce((a, item) =>
a[item] = (a[item] , );
return Object.values(itemCounts)
.reduce((pairsSoFar, count) => pairsSoFar + Math.floor(count / 2), 0);
console.log(pairNumber([10, 10, 10, 10, 20, 20, 20, 30, 50]))
Probably better to avoid .sort
if possible - that increases the computational complexity from O(n)
(minimum) to O(n log n)
.
I wonder if buildingitemCounts
doesn't add the sameO(nlogn)
back? How do objects work under the hood? Hashtables? Balanced trees?
– Vilx-
8 hours ago
For any remotely sane implementation, it'll beO(1)
, luckily: stackoverflow.com/questions/7700987/… . If using an object causes an issue, could use a Map instead
– CertainPerformance
8 hours ago
add a comment |
I'd reduce into an object, counting up the number of occurrences of each number. Then reduce again on the Object.values
of the object to count up the number of pairs, adding Math.floor(count / 2)
to the accumulator on each iteration:
function pairNumber(arr)
const itemCounts = arr.reduce((a, item) =>
a[item] = (a[item] , );
return Object.values(itemCounts)
.reduce((pairsSoFar, count) => pairsSoFar + Math.floor(count / 2), 0);
console.log(pairNumber([10, 10, 10, 10, 20, 20, 20, 30, 50]))
Probably better to avoid .sort
if possible - that increases the computational complexity from O(n)
(minimum) to O(n log n)
.
I wonder if buildingitemCounts
doesn't add the sameO(nlogn)
back? How do objects work under the hood? Hashtables? Balanced trees?
– Vilx-
8 hours ago
For any remotely sane implementation, it'll beO(1)
, luckily: stackoverflow.com/questions/7700987/… . If using an object causes an issue, could use a Map instead
– CertainPerformance
8 hours ago
add a comment |
I'd reduce into an object, counting up the number of occurrences of each number. Then reduce again on the Object.values
of the object to count up the number of pairs, adding Math.floor(count / 2)
to the accumulator on each iteration:
function pairNumber(arr)
const itemCounts = arr.reduce((a, item) =>
a[item] = (a[item] , );
return Object.values(itemCounts)
.reduce((pairsSoFar, count) => pairsSoFar + Math.floor(count / 2), 0);
console.log(pairNumber([10, 10, 10, 10, 20, 20, 20, 30, 50]))
Probably better to avoid .sort
if possible - that increases the computational complexity from O(n)
(minimum) to O(n log n)
.
I'd reduce into an object, counting up the number of occurrences of each number. Then reduce again on the Object.values
of the object to count up the number of pairs, adding Math.floor(count / 2)
to the accumulator on each iteration:
function pairNumber(arr)
const itemCounts = arr.reduce((a, item) =>
a[item] = (a[item] , );
return Object.values(itemCounts)
.reduce((pairsSoFar, count) => pairsSoFar + Math.floor(count / 2), 0);
console.log(pairNumber([10, 10, 10, 10, 20, 20, 20, 30, 50]))
Probably better to avoid .sort
if possible - that increases the computational complexity from O(n)
(minimum) to O(n log n)
.
function pairNumber(arr)
const itemCounts = arr.reduce((a, item) =>
a[item] = (a[item] , );
return Object.values(itemCounts)
.reduce((pairsSoFar, count) => pairsSoFar + Math.floor(count / 2), 0);
console.log(pairNumber([10, 10, 10, 10, 20, 20, 20, 30, 50]))
function pairNumber(arr)
const itemCounts = arr.reduce((a, item) =>
a[item] = (a[item] , );
return Object.values(itemCounts)
.reduce((pairsSoFar, count) => pairsSoFar + Math.floor(count / 2), 0);
console.log(pairNumber([10, 10, 10, 10, 20, 20, 20, 30, 50]))
answered 8 hours ago
CertainPerformanceCertainPerformance
130k17 gold badges86 silver badges116 bronze badges
130k17 gold badges86 silver badges116 bronze badges
I wonder if buildingitemCounts
doesn't add the sameO(nlogn)
back? How do objects work under the hood? Hashtables? Balanced trees?
– Vilx-
8 hours ago
For any remotely sane implementation, it'll beO(1)
, luckily: stackoverflow.com/questions/7700987/… . If using an object causes an issue, could use a Map instead
– CertainPerformance
8 hours ago
add a comment |
I wonder if buildingitemCounts
doesn't add the sameO(nlogn)
back? How do objects work under the hood? Hashtables? Balanced trees?
– Vilx-
8 hours ago
For any remotely sane implementation, it'll beO(1)
, luckily: stackoverflow.com/questions/7700987/… . If using an object causes an issue, could use a Map instead
– CertainPerformance
8 hours ago
I wonder if building
itemCounts
doesn't add the same O(nlogn)
back? How do objects work under the hood? Hashtables? Balanced trees?– Vilx-
8 hours ago
I wonder if building
itemCounts
doesn't add the same O(nlogn)
back? How do objects work under the hood? Hashtables? Balanced trees?– Vilx-
8 hours ago
For any remotely sane implementation, it'll be
O(1)
, luckily: stackoverflow.com/questions/7700987/… . If using an object causes an issue, could use a Map instead– CertainPerformance
8 hours ago
For any remotely sane implementation, it'll be
O(1)
, luckily: stackoverflow.com/questions/7700987/… . If using an object causes an issue, could use a Map instead– CertainPerformance
8 hours ago
add a comment |
If I understood the question well then this can be simplified even further by relying on sort initially...
Increment i to the next position after finding the pair and let the for loop increment it once again.
function pairNumber(arr)
var sorted_arr = [...arr].sort(); // disallowing array mutation
let cnt = 0;
for (let i = 0; i < sorted_arr.length; i++)
if (sorted_arr[i + 1] === sorted_arr[i])
cnt++;
i = i + 1;
return cnt;
console.log(pairNumber([10, 10, 10, 10, 10, 20, 20, 20, 20, 30, 30, 50]))
// 5 --> 2 pairs of 10, 2 pairs of 20, 1 pair of 30
console.log(pairNumbers([10, 10, 10, 10, 20, 20, 20, 30, 50]))
// 3 --> 2 pairs of 10 one pair of 20
1
I believesort
will mutate the original array, so a side-effect would be that the array being passed in will be sorted after calling this function.
– Matt Aft
7 hours ago
@MattAft tnx, edited my answer
– Eugene Sunic
7 hours ago
add a comment |
If I understood the question well then this can be simplified even further by relying on sort initially...
Increment i to the next position after finding the pair and let the for loop increment it once again.
function pairNumber(arr)
var sorted_arr = [...arr].sort(); // disallowing array mutation
let cnt = 0;
for (let i = 0; i < sorted_arr.length; i++)
if (sorted_arr[i + 1] === sorted_arr[i])
cnt++;
i = i + 1;
return cnt;
console.log(pairNumber([10, 10, 10, 10, 10, 20, 20, 20, 20, 30, 30, 50]))
// 5 --> 2 pairs of 10, 2 pairs of 20, 1 pair of 30
console.log(pairNumbers([10, 10, 10, 10, 20, 20, 20, 30, 50]))
// 3 --> 2 pairs of 10 one pair of 20
1
I believesort
will mutate the original array, so a side-effect would be that the array being passed in will be sorted after calling this function.
– Matt Aft
7 hours ago
@MattAft tnx, edited my answer
– Eugene Sunic
7 hours ago
add a comment |
If I understood the question well then this can be simplified even further by relying on sort initially...
Increment i to the next position after finding the pair and let the for loop increment it once again.
function pairNumber(arr)
var sorted_arr = [...arr].sort(); // disallowing array mutation
let cnt = 0;
for (let i = 0; i < sorted_arr.length; i++)
if (sorted_arr[i + 1] === sorted_arr[i])
cnt++;
i = i + 1;
return cnt;
console.log(pairNumber([10, 10, 10, 10, 10, 20, 20, 20, 20, 30, 30, 50]))
// 5 --> 2 pairs of 10, 2 pairs of 20, 1 pair of 30
console.log(pairNumbers([10, 10, 10, 10, 20, 20, 20, 30, 50]))
// 3 --> 2 pairs of 10 one pair of 20
If I understood the question well then this can be simplified even further by relying on sort initially...
Increment i to the next position after finding the pair and let the for loop increment it once again.
function pairNumber(arr)
var sorted_arr = [...arr].sort(); // disallowing array mutation
let cnt = 0;
for (let i = 0; i < sorted_arr.length; i++)
if (sorted_arr[i + 1] === sorted_arr[i])
cnt++;
i = i + 1;
return cnt;
console.log(pairNumber([10, 10, 10, 10, 10, 20, 20, 20, 20, 30, 30, 50]))
// 5 --> 2 pairs of 10, 2 pairs of 20, 1 pair of 30
console.log(pairNumbers([10, 10, 10, 10, 20, 20, 20, 30, 50]))
// 3 --> 2 pairs of 10 one pair of 20
edited 7 hours ago
answered 7 hours ago
Eugene SunicEugene Sunic
3,8284 gold badges32 silver badges50 bronze badges
3,8284 gold badges32 silver badges50 bronze badges
1
I believesort
will mutate the original array, so a side-effect would be that the array being passed in will be sorted after calling this function.
– Matt Aft
7 hours ago
@MattAft tnx, edited my answer
– Eugene Sunic
7 hours ago
add a comment |
1
I believesort
will mutate the original array, so a side-effect would be that the array being passed in will be sorted after calling this function.
– Matt Aft
7 hours ago
@MattAft tnx, edited my answer
– Eugene Sunic
7 hours ago
1
1
I believe
sort
will mutate the original array, so a side-effect would be that the array being passed in will be sorted after calling this function.– Matt Aft
7 hours ago
I believe
sort
will mutate the original array, so a side-effect would be that the array being passed in will be sorted after calling this function.– Matt Aft
7 hours ago
@MattAft tnx, edited my answer
– Eugene Sunic
7 hours ago
@MattAft tnx, edited my answer
– Eugene Sunic
7 hours ago
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57837661%2freturn-only-the-number-of-paired-values-in-array-javascript%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown