What is the process for removing items from an array in JavaScript that share the same values?

If you have an array of objects structured like the following:

   "medios":[  
      {  
         "Key":"1",
         "Text":"Cheque"
      },
      {  
         "Key":"2",
         "Text":"Tarjeta de Crédito"
      },
      {  
         "Key":"3",
         "Text":"Tarjeta de Crédito"
      },
      {  
         "Key":"4",
         "Text":"Tarjeta de Crédito"
      },
      {  
         "Key":"5",
         "Text":"Transferencia Bancaria"
      }
   ]

You want to remove objects with duplicate "Text" values, keeping only one of each. How can you accomplish this task?

One approach is to iterate over the array using a loop, but you may be unsure of how to target and delete the specific objects.

Answer №1

To avoid adding elements that are already present, you can utilize the reduce method.

var medios = [{"Key": "1","Text": "Cheque"},{"Key": "2","Text": "Tarjeta de Crédito"},{"Key": "3","Text": "Tarjeta de Crédito"},{"Key": "4","Text": "Tarjeta de Crédito"},{"Key": "5","Text": "Transferencia Bancaria"}];

medios = medios.reduce((c, n) =>
  c.find(el => el.Text == n.Text) ? c : [...c, n], []);
console.log(medios);

Answer №2

To ensure unique entries in your data, you can utilize a Map to key the information by Text. Then, you can extract the values from the map to reconstruct your array:

const obj = {"medios":[{ "Key":"1","Text":"Cheque"},{ "Key":"2","Text":"Tarjeta de Crédito"},{ "Key":"3","Text":"Tarjeta de Crédito"},{ "Key":"4","Text":"Tarjeta de Crédito"},{  "Key":"5","Text":"Transferencia Bancaria"}]};

obj.medios = Array.from(new Map(obj.medios.map(m => [m.Text, m])).values());

console.log(obj.medios);  

Answer №3

To filter out unwanted elements in an array, you can utilize the .filter() method along with a separate array to keep track of the existing elements. By doing this, you can create a new array that contains only the desired elements, ensuring that duplicates are removed. For example, in the given data set, keys 3 and 4 will be removed while key 2 will be retained in the new array.

const data = {
  "medios":[  
    {  
     "Key":"1",
     "Text":"Cheque"
    },
    {  
     "Key":"2",
     "Text":"Tarjeta de Crédito"
    },
    {  
     "Key":"3",
     "Text":"Tarjeta de Crédito"
    },
    {  
     "Key":"4",
     "Text":"Tarjeta de Crédito"
    },
    {  
     "Key":"5",
     "Text":"Transferencia Bancaria"
    }
   ]
};

const seen = [];

const result = {
  "medios": data.medios.filter( entry => {
    const already_seen = seen.includes( entry.Text );
    if ( already_seen ) return false;
    else {
      seen.push( entry.Text );
      return true;
    }
  })
};

console.log( result );

Answer №4

If you want to efficiently manage this situation, one great approach is to use the _.uniqBy() method from lodash:

const paymentMethods = [  
      {  
         "Key":"1",
         "Text":"Cheque"
      },
      {  
         "Key":"2",
         "Text":"Credit Card"
      },
      {  
         "Key":"3",
         "Text":"Credit Card"
      },
      {  
         "Key":"4",
         "Text":"Credit Card"
      },
      {  
         "Key":"5",
         "Text":"Bank Transfer"
      }
   ]


console.log(_.uniqBy(paymentMethods, 'Text'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Answer №5

To simplify and clean your code, consider using the _.uniqBy method from lodash like this:

// medios = [{Key: 1, Text: '' }, {Key: 2, Text: '' } ]
medios = _.uniqBy(medios, 'Text');

Answer №6

To efficiently filter out duplicate objects based on a specific text property, you can utilize the `reduce` method. Within the reduce callback function, employ the `find` method to determine if the accumulator array already contains an object with the same text. The `find` method will return a Boolean value. If it returns false, proceed to add the current object to the accumulator.

let medios = [{
    "Key": "1",
    "Text": "Cheque"
  },
  {
    "Key": "2",
    "Text": "Tarjeta de Crédito"
  },
  {
    "Key": "3",
    "Text": "Tarjeta de Crédito"
  },
  {
    "Key": "4",
    "Text": "Tarjeta de Crédito"
  },
  {
    "Key": "5",
    "Text": "Transferencia Bancaria"
  }
]
let filteredMedios = medios.reduce((acc, curr) => {
  let findText = acc.find((item) => {
    return item.Text.toLowerCase() === curr.Text.toLowerCase();
  });
  if (!findText) {
    acc.push(curr)
  }
  return acc;
}, []);

console.log(filteredMedios)

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

The outer DIV will envelop and grow taller in conjunction with the inner DIV

Could use a little help here. Thank you :) I'm having trouble figuring out how to get the outer div to wrap around the inner div and expand upwards with the content inside the inner editable div. The inner div should expand from bottom to top, and t ...

The v-on:click event handler is not functioning as expected in Vue.js

I am currently learning vue.js and facing some challenges. Below is the code snippet from my HTML page: <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.jsdelivr.net ...

What steps can be taken to fix a syntax error in a NodeJS express server code?

I am currently facing a syntax error in the code below, and I'm struggling to fix it. The specific error message is as follows: node staticapi.js /Users/v/Desktop/CS-Extra/EIP/A5/staticapi.js:123 res.status(200).send("Api is running") ...

Solving an object in ui-router state using ui-sref

Dealing with a large JSON object in an Angular controller and wanting to pass it to the controller of a template that will be displayed in a ui-view. I am aware that parameters can be passed to states using ui-sref, but I do not want this object to be visi ...

How can I extract a single specific element from a subdocument array?

I have a scenario where I am dealing with a document containing an array of applications that a user has joined. I need to retrieve a single document by user based on the application name. The code I have written so far works, but it retrieves all applic ...

XSL is the key component in creating a unique Custom Slider that remains stationary

I am currently working on a jQuery slider project and I am encountering an issue with getting the images to slide properly. The arrows seem to be functioning as expected, indicating that the necessary classes have been added, but the actual sliding action ...

State properties in Vuex remain unchangeable despite using mutator methods

I've encountered an issue with the code in my vuex module called user.js: import Vue from "vue"; import Vuex from 'vuex'; Vue.use(Vuex); const state = { user: { firstName: null, lastName: null, ...

Issue with primeng dropdown not displaying the selected label

When using the editable dropdown with filter feature from PrimeFaces, I've noticed that selecting an option displays the value instead of the label. https://i.sstatic.net/8YFRa.png Here is the code snippet: <div class="col-md-5 col-xs-1 ...

route in mean stack isn't providing a response

I am having trouble creating a controller for /projects that should return all the data in the 'work' collection. The call is completing successfully with a status code of 200, but it is only returning an empty array or 'test:test' if u ...

Exploring for JSON keys to find corresponding objects in an array and adding them to the table

I'm currently working on a project where I need to extract specific objects from a JSON based on an array and then display this data in a table. Here's how my situation looks: playerIDs: number[] = [ 1000, 1002, 1004 ] The JSON data that I am t ...

The execution of the 'yarn start-https' command encountered an error and exited with code 1

Struggling to set up the environment for a downloaded project. After running yarn install, yarn build, and yarn start-https, I encountered this error message: Error: error:0909006C:PEM routines:get_name:no start line at node:internal/tls/secure-context ...

Dynamically loading a JSON file in JavaScript

Can you please review this code snippet? var scripts = {}; require = function(src){ var id = Math.round(+new Date()/1000); $.ajax({ url: src + '.json', type: 'GET', dataType: "json", cache: ...

I'm facing a challenge where Multer is preventing me from showing images in my React app

Hi there, I'm currently facing an issue where I am using multer to save files on my server and store their path in mongodb. However, I am struggling to display them on my React application. Any assistance would be greatly appreciated. Thank you in ad ...

Querying through a database containing 1 million <string Name, int score> pairs efficiently within sub-linear time

My JSON object holds 1 million pairs. var student = {[ { name: "govi", score: "65" }, { name: "dharti", score: "80" }, { name: "Akash", score: "75" },............. up to a million ...

Utilizing an Async API call from a separate page and passing it as a component input

I recently set up an asynchronous API fetch in one of my .JS files and then invoked it from another JS file to output the result using console.log. (Is there a more efficient method for achieving this?) Now, my aim is to utilize the fields of the response ...

Difficulty encountered when trying to template routes with more than one slash in Angular-route

I'm encountering difficulties with my Express+Jade+AngularJS[v1.2.22] application when attempting to access routes such as "mydomain.com/something/somethingelse" or "mydomain.com/something/another/last", which include one or more path subdivisions. T ...

Are the arrays' values not matching up?

I have a challenge where I need to verify if two values from two separate arrays are equal. One value is retrieved from MySQL, and the other is obtained from the Facebook API. The user's location is represented by $UserHomeTown[1], while the friend&a ...

AngularJS - varying actions based on which input field I interacted with first

Here is the tutorial I referenced for this code: <!DOCTYPE html> <html> <head> <title>AngularJS Tutorials</title> <link rel="stylesheet" href="vendor/foundation/foundation.min.css"> </head> <body> & ...

Discovering the selected href URL using JQuery or JavaScript

How can I detect the clicked href URL using JQuery when no ID is being used? For example, if I have a list of links where some redirect to new pages and others call javascript functions to expand a div. What approach should be taken in JQuery/Javascript ...

Having issues with JavaScript function returning value from Ajax request

My AJAX request function is functioning well - returning 1 for success and 2 for failure. However, I am facing an issue when trying to perform actions outside of this function based on the return value. Instead of getting either 1 or 2, I always receive "u ...