Is there any method to combine the pair inside array to form a new array in java scriptInsert new item in array on any position in PHPSorting 2d matrix cols and rows in CCheck if arrays are the same without any key=>value pairsJava: Dividing pairs from an ArrayIn an input array in Java, how do I find the number of pairs of values that are equal?how to check if two json objects are equal in java?Equal elements in an unsorted arrayAdd multiple value obtained from spinner in CardView togetherHow can I input successive different values from a single vector across the same position in multiple arrays arranged in a list in R?

What do we gain with higher order logics?

Is it recommended against to open-source the code of a webapp?

Turing patterns

"Living" organ bank is it practical?

How to pass a regex when finding a directory path in bash?

Proof that shortest path with negative cycles is NP hard

What LISP compilers and interpreters were available for 8-bit machines?

How bad would a partial hash leak be, realistically?

PostgreSQL - Array of overlapping Polygon Ids

Average spam confidence

Company did not petition for visa in a timely manner. Is asking me to work from overseas, but wants me to take a paycut

About the expansion of seq_set_split

Did thousands of women die every year due to illegal abortions before Roe v. Wade?

Subtables with equal width?

Why is the application of an oracle function not a measurement?

How did students remember what to practise between lessons without any sheet music?

How to generate random points without duplication?

Incremental Ranges!

Implement Homestuck's Catenative Doomsday Dice Cascader

Russian equivalent of the French expression "broyer du noir"

How to translate “Me doing X” like in online posts?

The economics of a "no deal" Brexit

Axial Equatorial NMR graph difference

What happened to all the nuclear material being smuggled after the fall of the USSR?



Is there any method to combine the pair inside array to form a new array in java script


Insert new item in array on any position in PHPSorting 2d matrix cols and rows in CCheck if arrays are the same without any key=>value pairsJava: Dividing pairs from an ArrayIn an input array in Java, how do I find the number of pairs of values that are equal?how to check if two json objects are equal in java?Equal elements in an unsorted arrayAdd multiple value obtained from spinner in CardView togetherHow can I input successive different values from a single vector across the same position in multiple arrays arranged in a list in R?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








4















I am trying to arrange any kind of array input into a sorted array that also combines the equal pairs into an array inside the same array.



I do the following



const arrangeTheArray=(arr)=>

//checking input here
if(arr.length<2)

return arr;
else
//sorting the array
arr= arr.sort();

//displaying the sorted array
console.log(arr);
for(let i=1; i<arr.length;i++)

for(let j=0;j<i;j++)

//here I am looping and comparing the values of array
if(arr[j]===arr[i])
//putting the value
arr[j]= [arr[i],arr[j]];



//displaying the final output
console.log(arr);

arrangeTheArray([0,2,2,1,1,6,3,1,0])


e.g array input : [0,2,2,1,1,6,3,1,0]
final out put: [[0,0],[1,1,1],[2,2],3,6]










share|improve this question
























  • your sorting goes wrong for numbers greater then 9, becaus ou are sorting strings and not numbers.

    – Nina Scholz
    Mar 24 at 16:18












  • Sometimes I really mess up with logic so by doing sort(a,b=>return a-b)method would it solve the problem

    – jsLearner
    Mar 24 at 16:29

















4















I am trying to arrange any kind of array input into a sorted array that also combines the equal pairs into an array inside the same array.



I do the following



const arrangeTheArray=(arr)=>

//checking input here
if(arr.length<2)

return arr;
else
//sorting the array
arr= arr.sort();

//displaying the sorted array
console.log(arr);
for(let i=1; i<arr.length;i++)

for(let j=0;j<i;j++)

//here I am looping and comparing the values of array
if(arr[j]===arr[i])
//putting the value
arr[j]= [arr[i],arr[j]];



//displaying the final output
console.log(arr);

arrangeTheArray([0,2,2,1,1,6,3,1,0])


e.g array input : [0,2,2,1,1,6,3,1,0]
final out put: [[0,0],[1,1,1],[2,2],3,6]










share|improve this question
























  • your sorting goes wrong for numbers greater then 9, becaus ou are sorting strings and not numbers.

    – Nina Scholz
    Mar 24 at 16:18












  • Sometimes I really mess up with logic so by doing sort(a,b=>return a-b)method would it solve the problem

    – jsLearner
    Mar 24 at 16:29













4












4








4








I am trying to arrange any kind of array input into a sorted array that also combines the equal pairs into an array inside the same array.



I do the following



const arrangeTheArray=(arr)=>

//checking input here
if(arr.length<2)

return arr;
else
//sorting the array
arr= arr.sort();

//displaying the sorted array
console.log(arr);
for(let i=1; i<arr.length;i++)

for(let j=0;j<i;j++)

//here I am looping and comparing the values of array
if(arr[j]===arr[i])
//putting the value
arr[j]= [arr[i],arr[j]];



//displaying the final output
console.log(arr);

arrangeTheArray([0,2,2,1,1,6,3,1,0])


e.g array input : [0,2,2,1,1,6,3,1,0]
final out put: [[0,0],[1,1,1],[2,2],3,6]










share|improve this question
















I am trying to arrange any kind of array input into a sorted array that also combines the equal pairs into an array inside the same array.



I do the following



const arrangeTheArray=(arr)=>

//checking input here
if(arr.length<2)

return arr;
else
//sorting the array
arr= arr.sort();

//displaying the sorted array
console.log(arr);
for(let i=1; i<arr.length;i++)

for(let j=0;j<i;j++)

//here I am looping and comparing the values of array
if(arr[j]===arr[i])
//putting the value
arr[j]= [arr[i],arr[j]];



//displaying the final output
console.log(arr);

arrangeTheArray([0,2,2,1,1,6,3,1,0])


e.g array input : [0,2,2,1,1,6,3,1,0]
final out put: [[0,0],[1,1,1],[2,2],3,6]







javascript arrays






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 24 at 15:29









Code Maniac

15.1k21035




15.1k21035










asked Mar 24 at 15:19









jsLearnerjsLearner

574




574












  • your sorting goes wrong for numbers greater then 9, becaus ou are sorting strings and not numbers.

    – Nina Scholz
    Mar 24 at 16:18












  • Sometimes I really mess up with logic so by doing sort(a,b=>return a-b)method would it solve the problem

    – jsLearner
    Mar 24 at 16:29

















  • your sorting goes wrong for numbers greater then 9, becaus ou are sorting strings and not numbers.

    – Nina Scholz
    Mar 24 at 16:18












  • Sometimes I really mess up with logic so by doing sort(a,b=>return a-b)method would it solve the problem

    – jsLearner
    Mar 24 at 16:29
















your sorting goes wrong for numbers greater then 9, becaus ou are sorting strings and not numbers.

– Nina Scholz
Mar 24 at 16:18






your sorting goes wrong for numbers greater then 9, becaus ou are sorting strings and not numbers.

– Nina Scholz
Mar 24 at 16:18














Sometimes I really mess up with logic so by doing sort(a,b=>return a-b)method would it solve the problem

– jsLearner
Mar 24 at 16:29





Sometimes I really mess up with logic so by doing sort(a,b=>return a-b)method would it solve the problem

– jsLearner
Mar 24 at 16:29












3 Answers
3






active

oldest

votes


















1














You can use reduce and map.



Here idea is



  • First create a object with each digit as key and group the values by key.

  • Now map on the grouped data, if the length of element greater than one pass element as it is, else pass the 0th index value




let combine = (arr) =>
let groups = arr.reduce((op,inp)=>,)
let final = Object.values(groups).map(e=> e.length > 1 ? e : e[0])
return final


console.log(combine([0,2,2,1,1,6,3,1,0]))








const arrangeTheArray=(arr)=>
if(arr.length<2)

return arr;
else
arr = arr.sort((a,b)=>a-b);

let final = []
for(let i=0;i<arr.length;i++)
let current = arr[i]
let j = i;
let temp = []
while(arr[j] === current)
temp.push(arr[j])
j++

i = j-1
temp = temp.length > 1 ? temp : temp[0]
final.push(temp)

console.log(final)

arrangeTheArray([0,2,2,1,1,6,3,1,0])








share|improve this answer

























  • Well Thank you so much for your answer it is giving the desired output.I am facing little difficulties in understanding your code though. Can you tell me if I can achieve the same output using my code instead

    – jsLearner
    Mar 24 at 15:39











  • @jsLearner you can tell me where you're facing problem to understand will help you. wait let me update question with your version too

    – Code Maniac
    Mar 24 at 15:42











  • I gotta read and understand reduce properly. I was trying to achieve that with just arrays and for loop. So far i was able to sort the array and even manager to combine few pairs but that does not give the correct answer for all the inputs

    – jsLearner
    Mar 24 at 15:56






  • 1





    This works however the best answer should be the first way you mentioned

    – jsLearner
    Mar 24 at 16:15






  • 1





    map and filter i knew but could not think if we can use it here...gotta work on programming logic alot I am still learning

    – jsLearner
    Mar 24 at 16:18


















1














You can use Array.reduce to accumulate the common elements in an object.



Then use Object.values and Array.from to process the nested arrays into arrays of common elements and distinct elements:






const arrangeTheArray = (arr) => 
if (!Array.isArray(arr) && arr.length < 2)
return arr;

const pairs = arr.reduce((acc, ele) =>
if(acc[ele])
acc[ele].push(ele);
else
acc[ele] = [ele];

return acc;
, );
return Array.from(Object.values(pairs), ele => ele.length > 1 ? ele : +ele.join())


console.log(arrangeTheArray([0,2,2,1,1,6,3,1,0]));








share|improve this answer




















  • 1





    thanks for your answer let me check

    – jsLearner
    Mar 24 at 15:59


















1














You could sort the array with a callback for numbers and reduce the array by checking the predecessor p and the actual value v and push either the value or an array of the last group and the value.






function arrangeTheArray(array) 
return array
.sort((a, b) => a - b)
.reduce(
(r, v, i, [i - 1]: p ) => r.concat([p !== v ? v : [].concat(r.pop(), v)]),
[]
);


console.log(arrangeTheArray([0, 2, 2, 1, 1, 6, 3, 1, 0]));

.as-console-wrapper max-height: 100% !important; top: 0; 





With a classsic while loop from the end, because the array shrinks.






function arrangeTheArray(array) 
var i = array.length - 1;
array.sort((a, b) => a - b);
while (i--)
if (array[i] === (Array.isArray(array[i + 1]) ? array[i + 1][0] : array[i + 1]))
array[i] = [].concat(array[i], ...array.splice(i + 1, 1));


return array;


console.log(arrangeTheArray([0, 2, 2, 1, 1, 6, 3, 1, 0]));

.as-console-wrapper max-height: 100% !important; top: 0; 








share|improve this answer

























  • this looks good, thanks for the answer gotta read the reduce method once. But can we do it with for loop as well the one which I am trying ?

    – jsLearner
    Mar 24 at 15:49











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/3.0/"u003ecc by-sa 3.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
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55325281%2fis-there-any-method-to-combine-the-pair-inside-array-to-form-a-new-array-in-java%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









1














You can use reduce and map.



Here idea is



  • First create a object with each digit as key and group the values by key.

  • Now map on the grouped data, if the length of element greater than one pass element as it is, else pass the 0th index value




let combine = (arr) =>
let groups = arr.reduce((op,inp)=>,)
let final = Object.values(groups).map(e=> e.length > 1 ? e : e[0])
return final


console.log(combine([0,2,2,1,1,6,3,1,0]))








const arrangeTheArray=(arr)=>
if(arr.length<2)

return arr;
else
arr = arr.sort((a,b)=>a-b);

let final = []
for(let i=0;i<arr.length;i++)
let current = arr[i]
let j = i;
let temp = []
while(arr[j] === current)
temp.push(arr[j])
j++

i = j-1
temp = temp.length > 1 ? temp : temp[0]
final.push(temp)

console.log(final)

arrangeTheArray([0,2,2,1,1,6,3,1,0])








share|improve this answer

























  • Well Thank you so much for your answer it is giving the desired output.I am facing little difficulties in understanding your code though. Can you tell me if I can achieve the same output using my code instead

    – jsLearner
    Mar 24 at 15:39











  • @jsLearner you can tell me where you're facing problem to understand will help you. wait let me update question with your version too

    – Code Maniac
    Mar 24 at 15:42











  • I gotta read and understand reduce properly. I was trying to achieve that with just arrays and for loop. So far i was able to sort the array and even manager to combine few pairs but that does not give the correct answer for all the inputs

    – jsLearner
    Mar 24 at 15:56






  • 1





    This works however the best answer should be the first way you mentioned

    – jsLearner
    Mar 24 at 16:15






  • 1





    map and filter i knew but could not think if we can use it here...gotta work on programming logic alot I am still learning

    – jsLearner
    Mar 24 at 16:18















1














You can use reduce and map.



Here idea is



  • First create a object with each digit as key and group the values by key.

  • Now map on the grouped data, if the length of element greater than one pass element as it is, else pass the 0th index value




let combine = (arr) =>
let groups = arr.reduce((op,inp)=>,)
let final = Object.values(groups).map(e=> e.length > 1 ? e : e[0])
return final


console.log(combine([0,2,2,1,1,6,3,1,0]))








const arrangeTheArray=(arr)=>
if(arr.length<2)

return arr;
else
arr = arr.sort((a,b)=>a-b);

let final = []
for(let i=0;i<arr.length;i++)
let current = arr[i]
let j = i;
let temp = []
while(arr[j] === current)
temp.push(arr[j])
j++

i = j-1
temp = temp.length > 1 ? temp : temp[0]
final.push(temp)

console.log(final)

arrangeTheArray([0,2,2,1,1,6,3,1,0])








share|improve this answer

























  • Well Thank you so much for your answer it is giving the desired output.I am facing little difficulties in understanding your code though. Can you tell me if I can achieve the same output using my code instead

    – jsLearner
    Mar 24 at 15:39











  • @jsLearner you can tell me where you're facing problem to understand will help you. wait let me update question with your version too

    – Code Maniac
    Mar 24 at 15:42











  • I gotta read and understand reduce properly. I was trying to achieve that with just arrays and for loop. So far i was able to sort the array and even manager to combine few pairs but that does not give the correct answer for all the inputs

    – jsLearner
    Mar 24 at 15:56






  • 1





    This works however the best answer should be the first way you mentioned

    – jsLearner
    Mar 24 at 16:15






  • 1





    map and filter i knew but could not think if we can use it here...gotta work on programming logic alot I am still learning

    – jsLearner
    Mar 24 at 16:18













1












1








1







You can use reduce and map.



Here idea is



  • First create a object with each digit as key and group the values by key.

  • Now map on the grouped data, if the length of element greater than one pass element as it is, else pass the 0th index value




let combine = (arr) =>
let groups = arr.reduce((op,inp)=>,)
let final = Object.values(groups).map(e=> e.length > 1 ? e : e[0])
return final


console.log(combine([0,2,2,1,1,6,3,1,0]))








const arrangeTheArray=(arr)=>
if(arr.length<2)

return arr;
else
arr = arr.sort((a,b)=>a-b);

let final = []
for(let i=0;i<arr.length;i++)
let current = arr[i]
let j = i;
let temp = []
while(arr[j] === current)
temp.push(arr[j])
j++

i = j-1
temp = temp.length > 1 ? temp : temp[0]
final.push(temp)

console.log(final)

arrangeTheArray([0,2,2,1,1,6,3,1,0])








share|improve this answer















You can use reduce and map.



Here idea is



  • First create a object with each digit as key and group the values by key.

  • Now map on the grouped data, if the length of element greater than one pass element as it is, else pass the 0th index value




let combine = (arr) =>
let groups = arr.reduce((op,inp)=>,)
let final = Object.values(groups).map(e=> e.length > 1 ? e : e[0])
return final


console.log(combine([0,2,2,1,1,6,3,1,0]))








const arrangeTheArray=(arr)=>
if(arr.length<2)

return arr;
else
arr = arr.sort((a,b)=>a-b);

let final = []
for(let i=0;i<arr.length;i++)
let current = arr[i]
let j = i;
let temp = []
while(arr[j] === current)
temp.push(arr[j])
j++

i = j-1
temp = temp.length > 1 ? temp : temp[0]
final.push(temp)

console.log(final)

arrangeTheArray([0,2,2,1,1,6,3,1,0])








let combine = (arr) =>
let groups = arr.reduce((op,inp)=>,)
let final = Object.values(groups).map(e=> e.length > 1 ? e : e[0])
return final


console.log(combine([0,2,2,1,1,6,3,1,0]))





let combine = (arr) =>
let groups = arr.reduce((op,inp)=>,)
let final = Object.values(groups).map(e=> e.length > 1 ? e : e[0])
return final


console.log(combine([0,2,2,1,1,6,3,1,0]))





const arrangeTheArray=(arr)=>
if(arr.length<2)

return arr;
else
arr = arr.sort((a,b)=>a-b);

let final = []
for(let i=0;i<arr.length;i++)
let current = arr[i]
let j = i;
let temp = []
while(arr[j] === current)
temp.push(arr[j])
j++

i = j-1
temp = temp.length > 1 ? temp : temp[0]
final.push(temp)

console.log(final)

arrangeTheArray([0,2,2,1,1,6,3,1,0])





const arrangeTheArray=(arr)=>
if(arr.length<2)

return arr;
else
arr = arr.sort((a,b)=>a-b);

let final = []
for(let i=0;i<arr.length;i++)
let current = arr[i]
let j = i;
let temp = []
while(arr[j] === current)
temp.push(arr[j])
j++

i = j-1
temp = temp.length > 1 ? temp : temp[0]
final.push(temp)

console.log(final)

arrangeTheArray([0,2,2,1,1,6,3,1,0])






share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 24 at 16:10

























answered Mar 24 at 15:22









Code ManiacCode Maniac

15.1k21035




15.1k21035












  • Well Thank you so much for your answer it is giving the desired output.I am facing little difficulties in understanding your code though. Can you tell me if I can achieve the same output using my code instead

    – jsLearner
    Mar 24 at 15:39











  • @jsLearner you can tell me where you're facing problem to understand will help you. wait let me update question with your version too

    – Code Maniac
    Mar 24 at 15:42











  • I gotta read and understand reduce properly. I was trying to achieve that with just arrays and for loop. So far i was able to sort the array and even manager to combine few pairs but that does not give the correct answer for all the inputs

    – jsLearner
    Mar 24 at 15:56






  • 1





    This works however the best answer should be the first way you mentioned

    – jsLearner
    Mar 24 at 16:15






  • 1





    map and filter i knew but could not think if we can use it here...gotta work on programming logic alot I am still learning

    – jsLearner
    Mar 24 at 16:18

















  • Well Thank you so much for your answer it is giving the desired output.I am facing little difficulties in understanding your code though. Can you tell me if I can achieve the same output using my code instead

    – jsLearner
    Mar 24 at 15:39











  • @jsLearner you can tell me where you're facing problem to understand will help you. wait let me update question with your version too

    – Code Maniac
    Mar 24 at 15:42











  • I gotta read and understand reduce properly. I was trying to achieve that with just arrays and for loop. So far i was able to sort the array and even manager to combine few pairs but that does not give the correct answer for all the inputs

    – jsLearner
    Mar 24 at 15:56






  • 1





    This works however the best answer should be the first way you mentioned

    – jsLearner
    Mar 24 at 16:15






  • 1





    map and filter i knew but could not think if we can use it here...gotta work on programming logic alot I am still learning

    – jsLearner
    Mar 24 at 16:18
















Well Thank you so much for your answer it is giving the desired output.I am facing little difficulties in understanding your code though. Can you tell me if I can achieve the same output using my code instead

– jsLearner
Mar 24 at 15:39





Well Thank you so much for your answer it is giving the desired output.I am facing little difficulties in understanding your code though. Can you tell me if I can achieve the same output using my code instead

– jsLearner
Mar 24 at 15:39













@jsLearner you can tell me where you're facing problem to understand will help you. wait let me update question with your version too

– Code Maniac
Mar 24 at 15:42





@jsLearner you can tell me where you're facing problem to understand will help you. wait let me update question with your version too

– Code Maniac
Mar 24 at 15:42













I gotta read and understand reduce properly. I was trying to achieve that with just arrays and for loop. So far i was able to sort the array and even manager to combine few pairs but that does not give the correct answer for all the inputs

– jsLearner
Mar 24 at 15:56





I gotta read and understand reduce properly. I was trying to achieve that with just arrays and for loop. So far i was able to sort the array and even manager to combine few pairs but that does not give the correct answer for all the inputs

– jsLearner
Mar 24 at 15:56




1




1





This works however the best answer should be the first way you mentioned

– jsLearner
Mar 24 at 16:15





This works however the best answer should be the first way you mentioned

– jsLearner
Mar 24 at 16:15




1




1





map and filter i knew but could not think if we can use it here...gotta work on programming logic alot I am still learning

– jsLearner
Mar 24 at 16:18





map and filter i knew but could not think if we can use it here...gotta work on programming logic alot I am still learning

– jsLearner
Mar 24 at 16:18













1














You can use Array.reduce to accumulate the common elements in an object.



Then use Object.values and Array.from to process the nested arrays into arrays of common elements and distinct elements:






const arrangeTheArray = (arr) => 
if (!Array.isArray(arr) && arr.length < 2)
return arr;

const pairs = arr.reduce((acc, ele) =>
if(acc[ele])
acc[ele].push(ele);
else
acc[ele] = [ele];

return acc;
, );
return Array.from(Object.values(pairs), ele => ele.length > 1 ? ele : +ele.join())


console.log(arrangeTheArray([0,2,2,1,1,6,3,1,0]));








share|improve this answer




















  • 1





    thanks for your answer let me check

    – jsLearner
    Mar 24 at 15:59















1














You can use Array.reduce to accumulate the common elements in an object.



Then use Object.values and Array.from to process the nested arrays into arrays of common elements and distinct elements:






const arrangeTheArray = (arr) => 
if (!Array.isArray(arr) && arr.length < 2)
return arr;

const pairs = arr.reduce((acc, ele) =>
if(acc[ele])
acc[ele].push(ele);
else
acc[ele] = [ele];

return acc;
, );
return Array.from(Object.values(pairs), ele => ele.length > 1 ? ele : +ele.join())


console.log(arrangeTheArray([0,2,2,1,1,6,3,1,0]));








share|improve this answer




















  • 1





    thanks for your answer let me check

    – jsLearner
    Mar 24 at 15:59













1












1








1







You can use Array.reduce to accumulate the common elements in an object.



Then use Object.values and Array.from to process the nested arrays into arrays of common elements and distinct elements:






const arrangeTheArray = (arr) => 
if (!Array.isArray(arr) && arr.length < 2)
return arr;

const pairs = arr.reduce((acc, ele) =>
if(acc[ele])
acc[ele].push(ele);
else
acc[ele] = [ele];

return acc;
, );
return Array.from(Object.values(pairs), ele => ele.length > 1 ? ele : +ele.join())


console.log(arrangeTheArray([0,2,2,1,1,6,3,1,0]));








share|improve this answer















You can use Array.reduce to accumulate the common elements in an object.



Then use Object.values and Array.from to process the nested arrays into arrays of common elements and distinct elements:






const arrangeTheArray = (arr) => 
if (!Array.isArray(arr) && arr.length < 2)
return arr;

const pairs = arr.reduce((acc, ele) =>
if(acc[ele])
acc[ele].push(ele);
else
acc[ele] = [ele];

return acc;
, );
return Array.from(Object.values(pairs), ele => ele.length > 1 ? ele : +ele.join())


console.log(arrangeTheArray([0,2,2,1,1,6,3,1,0]));








const arrangeTheArray = (arr) => 
if (!Array.isArray(arr) && arr.length < 2)
return arr;

const pairs = arr.reduce((acc, ele) =>
if(acc[ele])
acc[ele].push(ele);
else
acc[ele] = [ele];

return acc;
, );
return Array.from(Object.values(pairs), ele => ele.length > 1 ? ele : +ele.join())


console.log(arrangeTheArray([0,2,2,1,1,6,3,1,0]));





const arrangeTheArray = (arr) => 
if (!Array.isArray(arr) && arr.length < 2)
return arr;

const pairs = arr.reduce((acc, ele) =>
if(acc[ele])
acc[ele].push(ele);
else
acc[ele] = [ele];

return acc;
, );
return Array.from(Object.values(pairs), ele => ele.length > 1 ? ele : +ele.join())


console.log(arrangeTheArray([0,2,2,1,1,6,3,1,0]));






share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 24 at 15:51

























answered Mar 24 at 15:32









Amardeep BhowmickAmardeep Bhowmick

6,54421231




6,54421231







  • 1





    thanks for your answer let me check

    – jsLearner
    Mar 24 at 15:59












  • 1





    thanks for your answer let me check

    – jsLearner
    Mar 24 at 15:59







1




1





thanks for your answer let me check

– jsLearner
Mar 24 at 15:59





thanks for your answer let me check

– jsLearner
Mar 24 at 15:59











1














You could sort the array with a callback for numbers and reduce the array by checking the predecessor p and the actual value v and push either the value or an array of the last group and the value.






function arrangeTheArray(array) 
return array
.sort((a, b) => a - b)
.reduce(
(r, v, i, [i - 1]: p ) => r.concat([p !== v ? v : [].concat(r.pop(), v)]),
[]
);


console.log(arrangeTheArray([0, 2, 2, 1, 1, 6, 3, 1, 0]));

.as-console-wrapper max-height: 100% !important; top: 0; 





With a classsic while loop from the end, because the array shrinks.






function arrangeTheArray(array) 
var i = array.length - 1;
array.sort((a, b) => a - b);
while (i--)
if (array[i] === (Array.isArray(array[i + 1]) ? array[i + 1][0] : array[i + 1]))
array[i] = [].concat(array[i], ...array.splice(i + 1, 1));


return array;


console.log(arrangeTheArray([0, 2, 2, 1, 1, 6, 3, 1, 0]));

.as-console-wrapper max-height: 100% !important; top: 0; 








share|improve this answer

























  • this looks good, thanks for the answer gotta read the reduce method once. But can we do it with for loop as well the one which I am trying ?

    – jsLearner
    Mar 24 at 15:49















1














You could sort the array with a callback for numbers and reduce the array by checking the predecessor p and the actual value v and push either the value or an array of the last group and the value.






function arrangeTheArray(array) 
return array
.sort((a, b) => a - b)
.reduce(
(r, v, i, [i - 1]: p ) => r.concat([p !== v ? v : [].concat(r.pop(), v)]),
[]
);


console.log(arrangeTheArray([0, 2, 2, 1, 1, 6, 3, 1, 0]));

.as-console-wrapper max-height: 100% !important; top: 0; 





With a classsic while loop from the end, because the array shrinks.






function arrangeTheArray(array) 
var i = array.length - 1;
array.sort((a, b) => a - b);
while (i--)
if (array[i] === (Array.isArray(array[i + 1]) ? array[i + 1][0] : array[i + 1]))
array[i] = [].concat(array[i], ...array.splice(i + 1, 1));


return array;


console.log(arrangeTheArray([0, 2, 2, 1, 1, 6, 3, 1, 0]));

.as-console-wrapper max-height: 100% !important; top: 0; 








share|improve this answer

























  • this looks good, thanks for the answer gotta read the reduce method once. But can we do it with for loop as well the one which I am trying ?

    – jsLearner
    Mar 24 at 15:49













1












1








1







You could sort the array with a callback for numbers and reduce the array by checking the predecessor p and the actual value v and push either the value or an array of the last group and the value.






function arrangeTheArray(array) 
return array
.sort((a, b) => a - b)
.reduce(
(r, v, i, [i - 1]: p ) => r.concat([p !== v ? v : [].concat(r.pop(), v)]),
[]
);


console.log(arrangeTheArray([0, 2, 2, 1, 1, 6, 3, 1, 0]));

.as-console-wrapper max-height: 100% !important; top: 0; 





With a classsic while loop from the end, because the array shrinks.






function arrangeTheArray(array) 
var i = array.length - 1;
array.sort((a, b) => a - b);
while (i--)
if (array[i] === (Array.isArray(array[i + 1]) ? array[i + 1][0] : array[i + 1]))
array[i] = [].concat(array[i], ...array.splice(i + 1, 1));


return array;


console.log(arrangeTheArray([0, 2, 2, 1, 1, 6, 3, 1, 0]));

.as-console-wrapper max-height: 100% !important; top: 0; 








share|improve this answer















You could sort the array with a callback for numbers and reduce the array by checking the predecessor p and the actual value v and push either the value or an array of the last group and the value.






function arrangeTheArray(array) 
return array
.sort((a, b) => a - b)
.reduce(
(r, v, i, [i - 1]: p ) => r.concat([p !== v ? v : [].concat(r.pop(), v)]),
[]
);


console.log(arrangeTheArray([0, 2, 2, 1, 1, 6, 3, 1, 0]));

.as-console-wrapper max-height: 100% !important; top: 0; 





With a classsic while loop from the end, because the array shrinks.






function arrangeTheArray(array) 
var i = array.length - 1;
array.sort((a, b) => a - b);
while (i--)
if (array[i] === (Array.isArray(array[i + 1]) ? array[i + 1][0] : array[i + 1]))
array[i] = [].concat(array[i], ...array.splice(i + 1, 1));


return array;


console.log(arrangeTheArray([0, 2, 2, 1, 1, 6, 3, 1, 0]));

.as-console-wrapper max-height: 100% !important; top: 0; 








function arrangeTheArray(array) 
return array
.sort((a, b) => a - b)
.reduce(
(r, v, i, [i - 1]: p ) => r.concat([p !== v ? v : [].concat(r.pop(), v)]),
[]
);


console.log(arrangeTheArray([0, 2, 2, 1, 1, 6, 3, 1, 0]));

.as-console-wrapper max-height: 100% !important; top: 0; 





function arrangeTheArray(array) 
return array
.sort((a, b) => a - b)
.reduce(
(r, v, i, [i - 1]: p ) => r.concat([p !== v ? v : [].concat(r.pop(), v)]),
[]
);


console.log(arrangeTheArray([0, 2, 2, 1, 1, 6, 3, 1, 0]));

.as-console-wrapper max-height: 100% !important; top: 0; 





function arrangeTheArray(array) 
var i = array.length - 1;
array.sort((a, b) => a - b);
while (i--)
if (array[i] === (Array.isArray(array[i + 1]) ? array[i + 1][0] : array[i + 1]))
array[i] = [].concat(array[i], ...array.splice(i + 1, 1));


return array;


console.log(arrangeTheArray([0, 2, 2, 1, 1, 6, 3, 1, 0]));

.as-console-wrapper max-height: 100% !important; top: 0; 





function arrangeTheArray(array) 
var i = array.length - 1;
array.sort((a, b) => a - b);
while (i--)
if (array[i] === (Array.isArray(array[i + 1]) ? array[i + 1][0] : array[i + 1]))
array[i] = [].concat(array[i], ...array.splice(i + 1, 1));


return array;


console.log(arrangeTheArray([0, 2, 2, 1, 1, 6, 3, 1, 0]));

.as-console-wrapper max-height: 100% !important; top: 0; 






share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 24 at 16:22

























answered Mar 24 at 15:33









Nina ScholzNina Scholz

208k16117190




208k16117190












  • this looks good, thanks for the answer gotta read the reduce method once. But can we do it with for loop as well the one which I am trying ?

    – jsLearner
    Mar 24 at 15:49

















  • this looks good, thanks for the answer gotta read the reduce method once. But can we do it with for loop as well the one which I am trying ?

    – jsLearner
    Mar 24 at 15:49
















this looks good, thanks for the answer gotta read the reduce method once. But can we do it with for loop as well the one which I am trying ?

– jsLearner
Mar 24 at 15:49





this looks good, thanks for the answer gotta read the reduce method once. But can we do it with for loop as well the one which I am trying ?

– jsLearner
Mar 24 at 15:49

















draft saved

draft discarded
















































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.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55325281%2fis-there-any-method-to-combine-the-pair-inside-array-to-form-a-new-array-in-java%23new-answer', 'question_page');

);

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







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript