Sort the array and organize it by frequency

Given the input array:

 array = [ 1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20 ]

The expected output is:

 [ [ 1, 1, 1, 1 ], [ 2, 2, 2 ], 4, 5, 10, [ 20, 20 ], 391, 392, 591 ]

Using the following function to generate the result:

var array = [ 1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20]

function answer(ArrayFromAbove) {
  var length = array.length;
  for (var i = 0; i < length; i++) {
    for (var j = 0; j < (length - i - 1); j++) {
      if (array[j] > array[j + 1]) {
        var tmp = array[j];
        array[j] = array[j + 1];
        array[j + 1] = tmp;

      }
    }
  }
}
answer(array);
console.log(array);

Expected return value:

[ [ 1, 1, 1, 1 ], [ 2, 2, 2 ], 4, 5, 10, [ 20, 20 ], 391, 392, 591 ]

Answer №1

You may want to consider utilizing the reduce method instead. This involves tallying up the occurrences of each number, then cycling through the sorted entries and adding the value to the result array (either as an array if there are multiple values, or as a single number if there's only one):

const input = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20];
/* create an object like:
{
  "1": 4,
  "2": 3,
  "4": 1,
  "5": 1,
  "10": 1,
  "20": 2,
  "391": 1,
  "392": 1,
  "591": 1
} */
const inputCounts = input.reduce((a, num) => {
  a[num] = (a[num] || 0) + 1;
  return a;
}, {});

const output = Object.entries(inputCounts)
  // turn (string) key to number:
  .map(([key, val]) => [Number(key), val])
  .sort((a, b) => a[0] - b[0])
  .reduce((a, [num, count]) => {
    a.push(
      count === 1
      ? num
      : new Array(count).fill(num)
    );
    return a;
  }, []);
console.log(output);

Answer №2

To start with, eliminate duplicates in an array using the Set method and then sort the array using

<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort" rel="nofollow noreferrer">Array.prototype.sort()</a>
. After that, determine the count of each number in the array and populate a new Array with it before appending it to the output.

const array=[1,3,5,672,457,456,3,6,11,3,1,1,1,29,29]
function countNumbers(arr,num){
  return Array(arr.filter(x => x === num).length).fill(num);
}
const uniqueNums = [...new Set(array)].sort((a,b) => a - b);
const finalOutput = uniqueNums.map(uniqueNum => {
  let arr = countNumbers(array,uniqueNum);
  return (arr.length > 1) ? arr : uniqueNum;
})
console.log(finalOutput)

The above method involves looping through the array multiple times. You can achieve the same result by looping through the array only twice as demonstrated below:

let numbers = [1,3,5,672,457,456,3,6,11,3,1,1,1,29,29]
numbers = numbers.sort((a,b) => a-b);
const finalResult = [];
let tempArr = [];
for(let j = 0; j < numbers.length + 1; ++j){
  if(numbers[j - 1] === numbers[j] || j === 0){
    tempArr.push(numbers[j]);
  }
  else{
    finalResult.push((tempArr.length === 1) ? tempArr[0] : tempArr);
    tempArr = [numbers[j]];
  }
}
//finalResult.push(tempArr)
console.log(finalResult);

Answer №3

To determine the number of times each element appears, you can tally up the occurrences and organize them into arrays:

 const frequency = new Map();

 for(const item of elements.sort())
   frequency.set(item, (frequency.get(item) || 0) + 1);

const output = [];

for(const [count, item] of frequency.entries())
  output.push(new Array(count).fill(item));

Answer №4

To populate an array based on the number of occurrences of each unique number, you can utilize the reduce method and then fill the array accordingly.

var array = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20]

let reduced = array.reduce((op,inp) => {
    op[inp] ? op[inp]++ : (op[inp]=1);
    return op;
}, {})

let op = Object.keys(reduced).map(e => 
    (reduced[e] === 1 ? e : new Array(reduced[e]).fill(e)))
        .sort((a,b) => 
            (Array.isArray(a) ? a[0] : a) - (Array.isArray(b) ? b[0] : b))

console.log(op)

Answer №5

First, organize the array by grouping all numbers into sub-arrays. Then, replace those sub-arrays with a single element representing each.

var nums = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20]
function reorganize(arr){
arr.sort((a,b) => a - b);
var tempResult = [];
while(arr.length > 0){
var val = arr.shift();
if(tempResult.length == 0 || tempResult[tempResult.length-1][0] !== val){
tempResult.push([val]);
        }else{
tempResult[tempResult.length-1].push(val);
        }
    }

while(tempResult.length > 0){
var subArr = tempResult.shift();
if(subArr.length == 1) arr.push(subArr[0]);
else arr.push(subArr);
    }

}
reorganize(nums);
console.log(JSON.stringify(nums));

Answer №6

If you want to achieve this, here is what you can do:

  • Start by sorting the array using Array.sort
  • Next, utilize Array.reduce to generate the final array
    • For the initial value, simply add it to the resulting array
    • For all subsequent values, check if the last value in the resulting array is an array
    • If the last value is an array, compare the first value with the current one
      • If they match, append it to the existing array
      • If not, add it as a new entry in the main resulting array
    • If the last value is not an array, compare it with the current value
      • If they match, replace the element in the resulting array with an array of 2 identical values
      • If not, add it as a new entry in the main resulting array

let array = [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20];
let result = array.sort((a,b) => a-b).reduce((a,c) => {
  if(a.length) {
    let lastVal = a[a.length-1];
    if(Array.isArray(lastVal)) {
      if(lastVal[0] == c) lastVal.push(c);
      else a.push(c);
    } else if(lastVal == c) a[a.length-1] = [c,c];
    else a.push(c);
  }
  else a.push(c);
  return a;
}, []);

console.log(result);

Answer №7

Below is my own take on the problem:

var data = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20]

function rearrangeArray(input) {
  return input.sort((a,b) => a - b)
    .reduce((collection, nextItem) => {
      // First item, simply add it
      if (!collection.length) {
        collection.push(nextItem)
        return collection
      }
      let previous = collection.pop()
      if (Array.isArray(previous)) {
        let [ number ] = previous
        if (number === nextItem) {
          previous.push(nextItem)
          collection.push(previous)
          return collection
        } else {
          collection.push(previous, nextItem)
          return collection
        }
      } else if (previous === nextItem ) {
        collection.push([previous, nextItem])
        return collection
      } else {
        collection.push(previous, nextItem)
        return collection
      }
    }, []);
}

console.log(rearrangeArray(data));

Answer №8

const numbers = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20]
const sortedNumbers = []
const subArray = []
const length = numbers.length;
numbers.sort(function sortArray(a,b) {
    return a - b;
});
for(let i = 0; i < length; i++)
{
    if(subArray.length == 0 || subArray[0] == numbers[i])
    {
        subArray.push(numbers[i]);
    }
    else if(subArray.length > 1 && numbers[i] != subArray[0])
    {
        sortedNumbers.push(subArray);
        subArray = [numbers[i]];     
    }
    else if(subArray.length == 1 && numbers[i] != subArray[0])
    {
        sortedNumbers.push(subArray[0]);
        subArray = [numbers[i]];
    } 
}
if(subArray.length == 1)
{
    sortedNumbers.push(subArray[0]);
}
else
{
    sortedNumbers.push(subArray);
}
console.log(sortedNumbers);
//return(sortedNumbers);

Answer №9

Utilizing Array.reduce() and Array.sort() to aggregate the duplicates into an object, then sorting and mapping the elements into a fresh array based on the key of the duplicate objects.

const newArray=[1,2,4,591,392,391,2,5,10,2,1,1,1,20,20].sort((a,b)=> a - b);

let accumulator = newArray.reduce((accumulator, element, index, array) => {
   if(element === array[index+1] && accumulator[element]){
     accumulator[element] = accumulator[element].concat(element) ;
   } else if(element === array[index+1]){
    accumulator[element] = [element].concat(element);
   }
   return accumulator;
}, {});
let resultArray = newArray.filter((element, index, array) => element !== array[index+1]).map((element) => accumulator[element]? accumulator[element]: element);
console.log(resultArray);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing React Developer Tools to easily click a button

Currently, I am working on building a card in React with Material UI. Here is the layout: https://i.sstatic.net/CFS58.png The button labeled Sign out has the functionality to change its state from true to false using React developer tools. However, I am ...

The message "Missing property 'type' in type 'typeof WithXXX'" indicates an error

Currently, I am working on a project using React in combination with Typescript. My goal is to create a higher order component based on the react-dnd library. The problem arises within the DragSource section of the react-dnd component. Here is the relevant ...

Revise Script to Duplicate Alt Attribute onto Miniatures

I'm customizing a gallery plugin for a website that I am currently developing, aiming to add support for titles. The script I am using can be found here: DEMO: http://jquery.malsup.com/cycle/pager2.html CODE: All the functionalities are in place e ...

Display icon within ng-bind-html when the value is not true

Is there a way to integrate a fontawesome icon into ng-bind-html on ui-select based on a boolean value? <span ng-bind-html="project.IsActive == false && <i class="fa fa-ban" aria-hidden="true"></i> | highlight: $select.search">& ...

Here's a method for using a for loop in ReactJS to update the state when a certain condition is met. Loops can efficiently update the state without having to iterate

I am encountering difficulties with a for loop in React because I am new to the framework. The for loop should increase the count if a certain condition is met. Below you can find the code I am struggling with: class CountWalls extends React.Component{ ...

Having difficulty redirecting to a dynamic URL with Next.js

In my Next.js 14 project, I am working with a file upload feature in the /research/page.tsx file. This file receives user input files and sends them to a server-side API for processing. Below is the function responsible for handling this process: const han ...

Locate all the elements in one array that also exist in another - PHP

Looking to compare the elements of two arrays in PHP? I tried using in_array but no luck so far :/ Array 1 array( (int) 0 => '2', (int) 1 => '3' ) Array 2 array( (int) 0 => (int) 1, (int) 1 => (int) 2, (int) 2 => (in ...

Is it possible for an HTML5 video element to stream m3u files?

Hey there, I'm currently working on integrating a video player using the HTML5 video tag. The content I have is being provided by Brightcove and is in the form of an m3u file. Is it feasible to play this video using the HTML5 video tag? My understand ...

Utilizing Angular Filters to Assign Values to an Object within a Controller

I have a JSON example with multiple records, assuming that each name is unique. I am looking to filter out an object by name in the controller to avoid constant iteration through all the records using ng-repeat in my HTML. { "records": [ { "Name" : ...

Transferring information from JSON to HTML

Recently, I came across this handy design tool within our service that helps generate Gauge charts by simply adding a specific div class to the desired pages. <div class="gauge" id="g0" data-settings=' { "value": ...

The Dialog feature offered by jQuery-UI

Having just started with jQuery, I am looking to implement the jQuery-UI Dialog to display a message containing lengthy text to the user. My goal is to have a "More details" link in each row of my HTML table that will trigger the jQuery Dialog window to op ...

When a frameset is clicked on

Apologies for my limited English skills, as I am a novice in JavaScript. Seeking assistance! I currently have a website with a frameset consisting of left, top, and main sections. My goal is to incorporate a chat feature with a user list in the left frame ...

How to make Sails.js package accessible across all modules

Recently, I have been using Sails frequently and came across a common practice question. Whenever I need to use a specific NPM package multiple times in a project, I typically include it in my config/bootstrap.js file like this: module.exports.bootstrap = ...

"Transferring a variable from the parent Layout component to its children components in Next

I am trying to figure out how to effectively pass the variable 'country' from the Layout component to its children without using state management. Basically, I want to drill it down. import { useState, useEffect } from 'react' import La ...

What are the steps to decode a JSON response using jQuery?

Working on a fun little web app for my significant other and me to keep track of movies we want to watch together. I'm exploring using TheMovieDatabase.org's API (which only supports JSON) to simplify the process of adding movies to our list. The ...

AngularJS is failing to recognize the onload event when loading a URL

I am currently working with the AngularJS Framework and I have encountered an issue. My directive only seems to work when the window is fully loaded. screensCreators.directive('createscreen', function () { return { restrict: "A", ...

Transforming ANSI to UTF-8 in Java

I have a JSON-formatted string with characters like \u0025 that I need to convert into their actual character representations. Is there a direct method in Java to perform this conversion? Perhaps something like myString.convertToUTF-8();? I am util ...

What is the process for installing Angular version 1.1.5 using npm?

I have attempted: npm install <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81e0efe6f4ede0f3c1b0afb0afb4">[email protected]</a> However, I encountered an error: npm ERR! Error: version not found: 1.1.5 : angul ...

Leveraging NgRx for Managing Arrays

export class Ingredient { public name: string; public amount: number; constructor(name: string, amount: number) { this.name = name; this.amount = amount; } } List of Ingredients: export const initialIngredients: Ingredient ...

Evaluation of outgoing HTTP requests through acceptance testing was the primary focus

Is there a possibility for automated acceptance testing when specific network requests are required by a web application due to user interactions? This type of testing seems unconventional as online discussions and tutorials are lacking in this area. For e ...