Eliminate redundant sets of comma-separated numbers from the jQuery input text value

On my webpage, there is an input with a value that looks like this: 1,7,1,4,22,58,58,1,1,4,7

<input type="text" name="hello" id="thankyouforhelping" value="" aria-invalid="false">

I have attempted multiple methods to remove the duplicate numbers from it but none of them have been successful. I tried searching for solutions on jQuery function to get all unique elements from an array? and jQuery function to get all unique elements from an array?

This is how I retrieve the value:

/* Getting latest value to eliminate duplicates */
$upToDateValue = $('.wdrow-'+$projectrow+' .tasks-created input').val();

The values are always numerical and comma-separated. How can I remove the duplicate numbers and also sort them from lowest to highest?

Ultimately, I want the result to be 1,4,7,22,58

/* Eliminating duplicates */
$newValue = ???;

PS: Most of the answers I found were in JavaScript but my code is written in jQuery, making it difficult for me to adapt those solutions. Apologies for the similarity of this question to others already posted. Questions similar to mine: Get all unique values in a JavaScript array (remove duplicates) I am unsure how to apply the accepted answers to my code.

Thank you everyone for your assistance!

##Heretic_Monkey provided a lot of help and the following is the outcome:

$upToDateValue = $('.wdrow-'+$projectrow+' .tasks-created input').val();
/* Removing duplicates */
var values = $upToDateValue.split(',');
values = [...new Set(values)];
values.sort();
$newValue = values.join(',');
/* Updating input with new value */
$('.wdrow-'+$projectrow+' .tasks-created input').val($newValue);

Answer №1

By combining insights from various sources such as How to convert a comma separated string to an array?, Easy way to turn JavaScript array into comma-separated list?, and Get all unique values in a JavaScript array (remove duplicates), here is a method to achieve the desired outcome:

// Obtain the value
var $upToDateValue = $('.wdrow-'+$projectrow+' .tasks-created input').val();
// Split the value into an array
var values = $upToDateValue.split(','); 
// Eliminate duplicate elements and create a new array without them
values = [...new Set(values)]; 
// Sort the new array
values.sort(); 
// Generate a new comma-delimited string from the array
var $newValue = values.join(',');
// Update the input field with the new value
$('.wdrow-'+$projectrow+' .tasks-created input').val($newValue);

Here are some references for the code utilized:

Answer №2

If you need a solution, feel free to use the updated code by copying the function and pasting it into your own code.

Afterwards, simply call the function in your code using $newValue = unique(values)

Check out this revised code:

function unique (value) {

  const valueList = value.split(",")
  const unique = valueList.filter((item, index, valueList) => {
    return index === valueList.indexOf(item);
  });
  const sorted = unique.sort(function(a, b) { return a - b; });
  
  return sorted.join(',')
}


/* Here's how you can implement it */
const value = "1,7,1,4,22,58,58,1,1,4,7"
$newValue = unique(value)

/* debug/print the result */
console.log($newValue)

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

Using the ref callback to access getBoundingClientRect values in React Components

I'm having some trouble extracting data using the getBoundingClientRect() method from a set of animated div elements. The issue I'm facing is that the refCallback function is returning empty DOMRect objects. If you're interested, feel free t ...

What could be the reason why I am unable to load the ejs file?

https://i.stack.imgur.com/91bPg.png Issue: Unable to find the "index.ejs" view in the views directory ...

Is it possible to utilize gulp to eliminate all require.js define([...]) wrappers throughout the codebase?

Is it possible to test my app without using require.js in order to assess the performance and file size if all files were concatenated into a single one? I'm contemplating using gulp to gather all *.js files in the app, running a gulp-replace to elim ...

Making a secure connection using AJAX and PHP to insert a new row into the database

Explaining this process might be a bit tricky, and I'm not sure if you all will be able to assist me, but I'll give it my best shot. Here's the sequence of steps I want the user to follow: User clicks on an image (either 'cowboys&apos ...

Having trouble invoking an established route within a different route in an Express JS project

While working with an Express JS application connected to a mySQL database, I encountered an issue when trying to fetch data from a pre-defined route/query: // customers.model.js CUSTOMERS.getAll = (result) => { let query = "SELECT * FROM custo ...

How to enhance and expand Material-UI components

I am trying to enhance the Tab component using ES6 class in this way: import React from "react"; import {Tab} from "material-ui"; class CustomTab extends Tab { constructor(props){ super(props); } render(){ return super.rende ...

The proper method for organizing a nested array object - an obstacle arises when attempting to sort the array

I have a collection of data fetched from Web API 2.2 stored in an Angular array as objects. Each object represents a Client and includes properties like name, surname, and a collection of contracts assigned to that client. Here is the interface definition ...

Utilizing Vue.js to dynamically add a class through computed properties

As a beginner in Vue.js, I want to dynamically add or remove classes based on certain conditions. Specifically, I am trying to remove the success class when the total sum exceeds 25, but for some reason the color is not changing as expected. Can anyone p ...

How can I utilize angular's $http service to fetch a JavaScript file?

I've been exploring the integration of Angular with Node.js and attempting to establish a connection to a MySQL database. Within my script (server.js), I am utilizing the node mysql module as shown below: var mysql=require('mysql'); var ...

When executing store.sync() in ExtJS, all fields are passed

In the latest version of ExtJS (6.5.0), I have set up a Store and an editable grid panel: Ext.define('StateStore',{ extend: 'Ext.data.Store', alias: 'store.stateStore', storeId : 'StateStore', field ...

Error: Jest react testing encountered an issue when attempting to read the property 'type' from an undefined value

While conducting tests on my app components created with the material UI library using jest and enzyme, I encountered an error in one of my packages. Here is a screenshot of the error: Click here to view ...

Revise a function that locates an object with a corresponding id in an array, modifies a property, and updates a React component's state

Here is a function that takes in a rating value within an object. The ID and Question properties remain unchanged, but the rating value can be updated. This will result in updating a React state value. Is there a method to improve the readability and con ...

Is it possible to create a grid by arranging each statement with a specific format?

After fetching and parsing some data, I have utilized the 'each' function to display it: $.ajax({ url : 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent('htt ...

Displaying server errors in an Angular componentIn this tutorial, we

As I work on creating a registration page, my focus has been on posting data to the server. I have successfully implemented client-side and server-side validation mechanisms. Managing client-side errors is straightforward using code such as *ngIf="(emailAd ...

Tips for concealing broken images in jQuery/JavaScript when generating dynamic content

Is there a way to hide the broken images in this dynamically generated HTML code using JavaScript? Unfortunately, I don't have access to the source code itself. I'm new to JQuery and could really use some assistance. Below is the snippet of the ...

Making sure the axios API call is completed before rendering the child component with props

Check out the snippet of code I've provided: function StoryCarousel(props) { const [ivrDests, setIVRDests] = useState([]); useEffect(() => { async function getIVRDests() { var data = { "customer-id": ...

"Feeling puzzled by the intricacies of the Jquery Timer

I am currently using the jQuery Timer plugin from to dynamically generate documents every 5 seconds with pause and resume functionality. Below is my script: $(function() { $('.handler').load("../Pages/csFetchCustomer.ashx?"); ...

Is there a way to maintain the loop filters in archive.php when using AJAX?

I've been following a tutorial on using AJAX with jQuery and WordPress to add posts to my Packery.js layout. It's working perfectly on my home page, but I'm running into issues when trying to implement it on my archive pages. Instead of disp ...

Can WikiData be accessed by providing a random pageId?

My current project involves creating a Wikipedia Search App with a 'Feel Lucky' button. I have been trying to figure out if it's possible to send a request for Wikidata using a specific pageid, similar to the code below: async function lucky ...

Ways to automatically refresh the div block's content whenever new data is added or updated in the database

Is there a way to automatically refresh the div block whenever there is activity in the database? I attempted using the setInterval function, but I'm looking for a solution that will update or insert data into the block based on updates made to the da ...