Looping through a JavaScript array, eliminating duplicates based on a specific value, and then adding the unique value along with another value to a new array

When receiving an array of objects through an API call in my Vuejs front-end application, I faced the task of looping through the data to eliminate duplicates and create a new array containing unique "phases" along with their respective "id's". The original array contained unnecessary key-value pairs, so I needed to filter them out. Additionally, I wanted the phases to be sorted in ascending order based on their phase numbers. Below is the code I used:

salesPhases () {
  let phases = this.$store.state.addresses.salesPhases
  let uniquePhases = []
  for (let i = 0; i < phases.length; i++) {
    if (uniquePhases.indexOf(phases[i].phase_number) === -1) {
      uniquePhases.push(phases[i].phase_number)
    }
  }
  return uniquePhases.sort((a, b) => {
    return a - b
  })
}

The code snippet above successfully achieved what I needed, except for including the id along with the phases. My attempt to include it resulted in losing the uniqueness condition as follows:

uniquePhases.push([phases[i].phase_number, phases[i].id])

Even though the sorting function continues to work, it now sorts a single-dimensional array that combines both phases and ids. An example snippet of the phases array structure is shown below:

{ "data": [
    {
        "id": "94e224af-135f-af31-3619-535acfae9930",
        "street_address1": "407 48TH ST E",
        "street_address2": null,
        "phase": "101",
        "sales_rep": "164",
        "id": "abd90d6b-28a8-2be6-d6c1-abd9007aef38",
        "name": "48TH ST E",
        "block_minimum": 400,
        "block_maximum": 498,
        "side": 2
    },
    {
        "id": "94e224af-135f-af31-3619-535acfae9930",
        "street_address1": "407 48TH ST E",
        "street_address2": null,
        "phase": "101",
        "sales_rep": "164",
        "id": "abd90d6b-28a8-2be6-d6c1-abd9007aef38",
        "name": "48TH ST E",
        "block_minimum": 401,
        "block_maximum": 499,
        "side": 1
    }
]

Answer №1

To extract only unique items from an array, you can utilize the filter method with a Set. Then, transform the filtered items into new objects containing just the id and phase_number, followed by arranging them based on the phase_number:

salesPhases () {
  const uSet = new Set()
  return this.$store.state.addresses.salesPhases
    .filter(({ phase_number }) => uSet.has(phase_number) ? false : uSet.add(phase_number)) // filter out duplicates by phase_number
    .map(({ id, phase_number }) => ({ id, phase_number })) // create an object with id and phase_number
    .sort((a, b) => a.phase_number - b.phase_number) // sort by phase_number
}

An alternative approach is to use the reduce method in conjunction with Map, then convert the resulting values of the Map into an array using the spread operator

salesPhases () {
  return [...this.$store.state.addresses.salesPhases
    .reduce((m, { id, phase_number }) => 
      m.has(phase_number) ? m : m.set(phase_number, { id, phase_number }), new Map()) // convert to map, prioritize unique phase_number keys
    .values()] // change Map values to an array
    .sort((a, b) => a.phase_number - b.phase_number) // sort by phase_number
}

Answer №2

To enhance your code functionality, consider updating it to push the complete phase object instead of just the phase number. Utilize the Array's find method in place of indexOf to verify if a phase with the specified number exists.

Give this approach a try:

updateSalesPhases () {
  let phases = this.$store.state.addresses.salesPhases
  let uniquePhases = []
  for (let i = 0; i < phases.length; i++) {
    if (!uniquePhases.find(x => x.phase_number === phases[i].phase_number)) {
      uniquePhases.push(phases[i])
    }
  }
  return uniquePhases.sort((a, b) => {
    return a.phase_number - b.phase_number
  })
}

Answer №3

To handle this scenario, I recommend utilizing the powerful tool lodash: https://lodash.com/docs#sortedUniqBy

fetchUniqueSalesPhases () {
  return _.sortedUniqBy(this.$store.state.addresses.salesPhases, 
    phase => phase.phase_number)
}

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

Search for and swap out every item in a multi-tiered array

I am working with an array where the first column represents an id: var mainarray = [ ["1001","P6","P8"], ["1002","P7"], ["1003","P7","P8","P10"], ["1004","P6","P10"], ]; My goal is to replace each 'P' element with its corresponding animal from ...

What is the best way to generate a fresh JSON object within a react hook function?

I am currently facing two issues. Firstly, I am having trouble figuring out how to add/update the JSON items within a hook. Secondly, React seems to be restricting me from using the name that is stored in a previous JSON file. I am open to exploring alter ...

In Vue3, a certain variable can be set either through props or using ref

// Here is some pseudo code for handling modelValue and image props = { modelValue? } image = ref() onPageLoad = function { if modelValue is null then: image.value = await api.get() } <button @onClick> // Displaying image based on condition ...

What is the process for selecting the default option in a drop-down menu?

Is there a way to set the default value in a drop-down list using material-ui? I attempted to use displayEmpty="true", but it did not work. I want the first option, A, to be pre-selected so that it is visible to the user in the UI without them having to m ...

Steps to include a fresh string into an array within a json document

I'm currently working on a Discord bot that uses a profile.json file. My goal is to have a specific command that allows users to add input arguments to an array within the file, like this: {"Profile_name":"id":"idhere", "array":["item_1"]} The ultim ...

Display or conceal several elements using JQUERY/HTML upon hovering

Here is the current progress: <div style="position: relative;"> <a href="#games"> <div class="sidenavOff"> <img src = "images/card_normal.png" /> <img src = "images/category_icons/icon_games.png" style = "position: a ...

Defining TypeScript type annotations: the art of declaring class constructors

I've developed my own JavaScript library (consisting of a single js file) with multiple classes. To incorporate it into my TypeScript projects, I created a d.ts file containing type definitions for each class. An example of the definition would be: ex ...

Problems arise when using AngularJS' .run function after navigating to a different page

I have encountered an issue with ngRoute while navigating between pages in my web application. The main login page is called index.html, and the routing is controlled by the main js file. However, I face a problem when trying to use a .run block on a speci ...

Retrieving the parent value in React-select grouped options

When using react-select with grouped options, the structure is as follows: { label: PARENT_NAME, value: PARENT_ID, options: [ { label: CHILD_NAME, value: CHILD_ID, } ] } An array of these options is passed to the component lik ...

The resolution of Q.all does not occur in the expected order

I'm currently facing an issue with the order in which promises are being executed in Node.js. The goal of the code is as follows: a) Run a query and use the resulting latitude/longitude pairs to b) Calculate the shortest paths (using an async funct ...

Retrieve the user_id without triggering any route

Is there a way to access the logged in user data without needing to make a request to any route or endpoint? //for example, how can I retrieve the id of the logged in user here? router.get('/',function(req,res,next){ //typically we would acce ...

What methods can I use to ensure precision in my raycasting while maneuvering the mouse over various sections of a LineSegment?

I have created a demonstration for drawing a LineSegment using three.js. I have implemented vertexColors in the material and assigned colors to the vertices. When hovering over different parts of the LineSegment, I change the color of the selected vertex ( ...

Implementing a file download feature in Python when clicking on a hyperlink

I'm attempting to click on the href link below. href="javascript:;" <div class="xlsdownload"> <a id="downloadOCTable" download="data-download.csv" href="javascript:;" onclick=&q ...

Is it possible to customize the color of the modal backdrop in layer v4 of the Material-UI library

I am struggling to modify the background color of an MUI V4 modal. Instead of getting a clean color, I am seeing a gray layer on top of the backdrop. Though this seems to be the default behavior, I want to remove it and target the shaded div directly rathe ...

Enhancing button functionality using jQuery and JavaScript for toggling behavior

I am facing a challenge with this code. The goal is to have a single script that can handle multiple audio elements on the page and toggle between PLAY and PAUSE buttons by adding or removing classes. Can anyone suggest any changes or additions that coul ...

Error encountered: Unexpected token '<' when using PHP and Jquery AJAX post

Hey everyone, I've been encountering a persistent issue with an uncaught syntax error: unexpected token <. The error seems to be originating from the jQuery library file. I am trying to make an AJAX request to comment-insert-ajax.php using JQuery i ...

The Iframe contains its own scroll feature within the body

I am facing an issue with displaying an Iframe inside a modal. The challenge is that the content within the Iframe varies in height, making it difficult to set a fixed height for the Iframe itself. When I try setting the height to 100%, the result is a 150 ...

Using VueJS: How can I reference a variable by its string name instead of directly in a template?

Is there a way to access a variable defined in a <script> tag in a template using its string name? For example, in the code snippet below, I want to access the foo variable using table[0]: <template> <div> {{ table[0] }} {{ tab ...

Adding byte arrays together in a repetitive sequence using Go

Seeking guidance in Go: I am a newcomer to the world of Go programming, and despite my efforts, I have been unable to find a solution for appending a byte slice. My goal is to separate the first line of a file, which I have managed to do; then store the re ...

Any ideas on how I can use PHP or JavaScript to repeatedly execute a segment of HTML code?

I recently tried using a for loop and heredoc in PHP with code that looks something like this: $options = ''; for($Year = date("Y"); $Year <= date("Y") + 5; $Year++) { $options .= "<option>$Year</option>\n"; } $Select = ...