skip to Main Content

Javascript – How to group same adjacent objects into an array (eg:[1,1,2,2,2,3,4,4,4] to [[1,1],[2,2,2],[3],[4,4,4]])?

For example, I have an array : [1,1,2,2,2,3,4,4,4], I want a result that group the same adjacent objects into another array : [[1,1],[2,2,2],[3],[4,4,4]], how can I do that? I tried: const arr=[1,1,2,2,2,3,4,4,4]; const result=[]; for(let i=0,j=1;j<arr.length;j++){ if(arr[j-1]!=arr[j]){ result.push(arr.slice(i,j)); i=j; }…

VIEW QUESTION
Back To Top
Search