What is the best way to sort and tally items within a JavaScript array?

I am currently working on implementing the filter method on an array that contains objects like the following:

{
  "start": 1234,
  "end": 4321,
  "count": 0
}

My goal is to remove duplicates from the array while incrementing the count property.

So far, I have successfully filtered the array based on the start property with this code snippet:

 var temp = {};
 myArray = myArray.filter(function(obj) {
     if (obj.start in temp) {
         return false;
     } else {
         temp[obj.start] = true;
         return true;
     }
 }); 

Now, I want to create a filter that follows these conditions (temporary object referred to as tempObj and current object as obj for clarity):

  • If obj.start === tempObj.start && obj.end === tempObj.end, obj.count += 1
  • If obj.start === tempObj.start || obj.end === tempObj.end, obj.count = tempObj.count + 1
  • If obj.start > tempObj.start && obj.end < tempObj.end, obj.count = tempObj.count + 1
  • Otherwise, add a new element to temp with count = 1

Is it achievable using the filter method? If not, what would be the correct approach? I prefer to avoid using any framework.

EDIT: Following RobG's request for clarification, here is an example of input and output:

Example input:

myArray = [{
  "start": 1105,
  "end": 1501,
  "count": 0
},

{
  "start": 1105,
  "end": 1003,
  "count": 0
},

{
  "start": 1110,
  "end": 1120,
  "count": 0
},

{
  "start": 1105,
  "end": 1003,
  "count": 0
},

{
  "start": 1115,
  "end": 1120,
  "count": 0
}]

Desired output:

myArray = [{
  "start": 1105,
  "end": 1501,
  "count": 1
},

{
  "start": 1105,
  "end": 1003,
  "count": 3
},

{
  "start": 1110,
  "end": 1120,
  "count": 1
}

{
  "start": 1115,
  "end": 1120,
  "count": 1
}]

Answer №1

Does this meet your requirements?

myArray = [{
    "start": 1105,
    "end": 1501,
    "count": 0
  },

  {
    "start": 1105,
    "end": 1003,
    "count": 0
  },

  {
    "start": 1110,
    "end": 1120,
    "count": 0
  },

  {
    "start": 1105,
    "end": 1003,
    "count": 0
  },

  {
    "start": 1115,
    "end": 1120,
    "count": 0
  }
]



var obj = {};

for (var i = 0, len = myArray.length; i < len; i++) {
  obj[myArray[i]['start']] = myArray[i];
}

myArray = new Array();
var count = 0;
for (var key in obj) {
  obj[key].count = count++;
  myArray.push(obj[key]);
}



console.log(myArray)

revised response

myArray = [{
    "start": 1105,
    "end": 1501,
    "count": 0
  },

  {
    "start": 1105,
    "end": 1003,
    "count": 0
  },
  {
    "start": 1105,
    "end": 1003,
    "count": 0
  },

  {
    "start": 1110,
    "end": 1120,
    "count": 0
  },

  {
    "start": 1105,
    "end": 1003,
    "count": 0
  },

  {
    "start": 1115,
    "end": 1120,
    "count": 0
  }
]


function removeDoopCount(myArray) {
  const start = x => myArray[x].start;
  const end = x => myArray[x].end;
  let hash = new Map();
  for (var i = 0, len = myArray.length; i < len; i++) {
    let key = start(i) + ':' + end(i);
    let item = myArray[i];
    let values = hash.get(key);
    if (values) values.push(item);
    else hash.set(key, [item]);
  }
  let ar = [];
  hash.forEach((v, k, m) => (count = 1, v.forEach(i => i.count += count++), ar.push(v[v.length - 1])));
  return ar;
}
console.log(removeDoopCount(myArray));

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

Is it possible to align a div on the same line with an h1 header that spans multiple lines using CSS?

I am currently working on the following code: <h1><span>Test Heading This is the text that I want to display on the right side. This is the text that I want to display on the right side. This is the text that I want</span></h1> < ...

Pattern matching for transforming object notation into an array of values

I'm attempting to transform objects specified in a file into arrays. My approach involves using JSON.parse on the identified objects. However, I'm encountering issues with certain multi-line objects not getting replaced correctly. const tx ...

Is it normal for a Firebase listener to trigger twice when adding date to the database in React?

I've developed a basic chat application. Once the user submits a message, it is stored in the database along with their username. this.ref.child("/chat").update({username: this.state.username, message: this.state.chatMessage}); Subsequently, I ...

Dealing with a null array triggering the error message "Uncaught (in promise) SyntaxError: Unexpected end of JSON input."

My react / redux / node express app is designed to manage patient information, but I'm facing a bug when trying to read new data after deleting a patient encounter. Everything works smoothly until the last encounter associated with the patient is dele ...

How can a nested struct array be constructed?

I am working on creating an array of 1000 positions in my code. Each position contains a struct with an int (acting as a counter) and a nested struct initialized as an array of 100 positions. I need to confirm if this design is correct. My goal is to crea ...

Understanding the responseText of an AJAX returned value

I need to handle a 401 exception when my AJAX call returns it. This is the snippet of my code: error: function(error) { var CevapHata = error.responseText.toString(); var pos=CevapHata.IndexOf("401"); } However, I am encountering an error when tr ...

Running JavaScript in selenium and obtaining the result

I'm currently utilizing JavaScript with Selenium WebDriver. Here is a snippet of my code: let return_value = driver.execute_script(script) However, I am unsure how to retrieve the value from my script. const token = await grecaptcha.enterprise.exec ...

Converting hierarchical JSON data into a table with rowspan using Angular

I am facing a challenge in creating a table using nested JSON obtained from an API. I am unsure how to dynamically merge cells when needed, especially since the JSON structure can be nested up to 6 or 7 levels. Desired Table : Expected Table Current Ou ...

Embedding a YouTube video in a view player using HTML5

So I've got a question: can you actually open a youtube video using an HTML5 video player? I'm looking for a more mobile-friendly way to watch youtube videos, and my idea was to upload a thumbnail image and then set up an onclick function to disp ...

The data retrieved from the $.ajax() request in Vue.js is not properly syncing with the table

After setting up an $.ajax() function and ensuring the data binding is correctly configured, I expected the data to append to a table on page load without any issues. However, the data is not appearing as expected. Is there something that I might be overlo ...

Create a regulation that permits access solely to individuals currently logged into the system database

I am a beginner when it comes to working with Firebase and its rules. My goal is to implement a system where each user in the Firestore database has a boolean field called isOnline, as shown in the image I have attached. https://i.stack.imgur.com/7M3dc.pn ...

Generate a text input field within a dropdown menu

Below is an example of my basic HTML code for a drop-down list: <span id="Div_List"> <label for="Gender">For:</label> <select name="Gender" id="Sex"> <option value="1">1000mtr</option> <option val ...

Having trouble with Node.js POST request; no specific error message displayed

Currently facing a challenge in communicating with an API using nodejs. I've exhausted all possible solutions, including utilizing different request modules and altering the format among other attempts. Here is the code snippet... var request = requ ...

Make sure a specific piece of code gets evaluated in a timely manner

To ensure the default timezone is set for all moment calls in the app's lifetime, I initially placed the setter in the entry point file. However, it turns out that this file is not the first to be evaluated. An issue arose with one of my reducers wher ...

Converting a comma-separated string into an array of integers using jQuery

Is there a way in jQuery to convert a string containing multiple numbers into an array? The string in question is as follows: let values = "901,235,342,421,345,745,544,324,445,123,232,986,345,678"; ...

Step-by-step guide: Adding a Google Maps API key to your WordPress theme

Having an issue with Google Maps on my WordPress website. The error message displayed is: Google Maps API error: MissingKeyMapError I have obtained a Google Maps API key, but I am unsure where to insert it. I am not using a Google Maps plugin; instead, my ...

Utilizing a Proxy with Vite for Vue Frontend in Conjunction with Django Rest Framework

Have you ever noticed the difference between accessing a view with Django Rest API on a browser versus sending an Ajax request and receiving JSON? I'm currently trying to modify the proxy settings for Vite, but I'm struggling to find comprehensiv ...

JavaScript: Redirect to a webpage with randomized sections within the address

When I access an HTML site, my goal is to automatically redirect to the following page: www.xyz.de?user=default&f1=OPTION1&f2=OPTION2&f3=OPTION3&f4=OPTION4&f5=OPTION5&... etc. To achieve this, I need to randomly select values for ...

Uncovering unseen tags generated by JavaScript on a webpage using Python

I have THIS LINK page that contains javascript. To view the javascript, simply click on show details. How can I extract data from this URL source? Should I use re? Here is what I attempted with re: import urllib import re gdoc = urllib.urlopen('Tha ...

Is there a way in HTML to navigate directly to a specific element on another page, even if it is not currently visible

I have used an anchor to navigate to a specific element on another page from the current page. However, the specific element I want to navigate to is not currently visible because it is controlled by JavaScript to keep the page short. The element is only s ...