JS : Removing duplicate elements from an array and replacing them with updated values

I have an array that looks like this:

let arr = ['11','44','66','88','77','00','66','11','66']

Within this array, there are duplicate elements:

  • '11' at position 7
  • '66' at positions 6 and 8

I need to loop through the array to identify duplicated elements and replace them from the second occurrence with a string indicating the index of the first occurrence.

The resulting array would be:

let newarr = ['11','44','66','88','77','00','appears at 2','appears at 0','appears at 2']

As shown, the duplicates are replaced with strings like:

"appears at n" where "n" represents the index of the first occurrence

Answer №1

Give this a shot:

const counts = {}
const values = ['red','blue','green','yellow','blue','green','red']

const newValues = values.map((value, idx) => {
  if (counts[value] !== undefined) return `already counted at ${counts[value]}`
  else {
    counts[value] = idx
    return value
  }
})

console.log("Updated values: ", newValues)

Answer №2

An innovative solution utilizing a closure with a hash table for indexing and a conditional operator

const
    data = ['11', '44', '66', '88', '77', '00', '66', '11', '66'],
    output = data.map(
        (indices => (val, index) => (indices[val] ??= index) == index ? val : `found at ${indices[val]}`)
        ({})
    );

console.log(output);

Answer №3

Check out this simple two-step approach:

  1. Initialize an object to track initial occurrences

  2. Map the original array to a new array with replacements

let numbers = ['11', '44', '66', '88', '77', '00', '66', '11', '66'];

// Record initial occurrences
const firstOccurrences = numbers.reduce((acc, val, index) => {
  if (typeof acc[val] === 'undefined') {
    acc[val] = index;
  }
  return acc;
}, {});

console.log('firstOccurrences:', firstOccurrences);

// Create a new array with replacements
const newArray = numbers.map((val, index) => {
  return (firstOccurrences[val] === index) ? val : `present at ${firstOccurrences[val]}`;
});

console.log(`newArray:`, newArray);

Answer №4

Answer

const numbers = ["11", "44", "66", "88", "77", "00", "66", "11", "66"].map(
  (val, index, arr) => {
    if (arr.indexOf(val, 0) !== index) {
      return `found at ${arr.indexOf(val, 0)}`;
    }
    return val;
  }
);
console.log(numbers);

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

What's the best way to pass parameters through Higher-Order Components in React?

my custom component App import React, { Component } from "react"; import City from "./City"; import withDataLoader from "./withDataLoader"; const MyApp = () => { const MyCity = withDataLoader( City, "https://5e5cf5eb97d2ea0014796f01.mockapi ...

Tips to swap selections in a Select2 dropdown box

Is there a way to dynamically clear a Select2 option list and reload it with new data? Despite setting the data as suggested, it seems to only append the new data without clearing the existing options. $("#optioner").select2(); $("#doit").click(functio ...

The AudioPlayerStatus module in Discord JS is a powerful tool for managing

Could you explain why this code snippet: client.player.once(AudioPlayerStatus.Idle, () => { console.log(client.playlist); next.run(message, args, client); client.playlist.shift(); return; }); is b ...

Retrieving information within a Vue component

I am struggling to access some data I have bound to a component without success. How can I achieve this? Below is my component: export default { name: 'component-vallingby', data() { return { } }, created() {}, methods: {} } And h ...

Discovering the technique to unearth a specific value within an array nested within another array

I am encountering an issue with finding a value in one array inside another array and utilizing the resulting value to update the state using setState(). Here is the initial state: this.state = { initialStudents:[ {name:"str1",tags;["str","s ...

Element UI: Triggering an event when the sort caret is clicked

Is it possible to trigger an event when the sorting carets are clicked on a table with sortable columns, ideally with the same parameters as the header-click event? I am able to emit an event by clicking on the header of any sortable column (header-click) ...

Troubleshooting iFrame Loading Issues with HTML5 PostMessage

Our code is utilizing the newest postMessage feature in HTML 5 to address cross-domain communication challenges. The issue I am facing is figuring out how to determine if the messages posted to an iFrame have been successfully loaded. If the frame fails to ...

Error in TypeScript while running the command "tsd install jquery" - the identifier "document" could not be found

Currently, I am facing an issue with importing jQuery into my TypeScript project. In order to achieve this, I executed the command tsd install jquery --save, which generated a jquery.d.ts file and added /// <reference path="jquery/jquery.d.ts" /> to ...

Utilizing Vue.js to initiate a server request with vue-resource

Seeking guidance on performing a server call using vue-resource. I'm unsure about how to set the header and send data via Vue.$http.post Vue.$http.post('http://url/', { email: 'foo', password: 'bar' }, { headers: { ...

Tips on implementing Dynamic arrays in the useEffect hook within React applications

Does anyone have experience with using a dynamic array as input in the dependency array of the useEffect hook? I'm encountering an issue where the array is being passed as a string and therefore not triggering the hook correctly. const [formData,setFo ...

Perform the function with the value of the currently selected option

Despite selecting an option, a message still appears stating "Please choose something." This function works with only one dropdown list, but encounters issues when there are two or more. (In this example, the variable 'sport' is document.getElem ...

AngularJS encounters an issue while attempting to print a PDF file

I am encountering an issue with printing a PDF file that was generated using reportViewer in my Web API. The browser displays an error when attempting to open the PDF file. Below is the code snippet from the controller in my Web API: // ...generate candi ...

Activate function on Selected DIV

Within this div, I have set the tabindex attribute to '-1' so that it can be focused on mouse click. <div tabindex='-1'></div> .div:focus{//some style} My goal is to use jQuery to perform an action when a user clicks on th ...

Unchecking and checking the radio button is necessary in order for it to function properly

Today, I'm puzzled by the odd behavior of my radio buttons in a pixel drawer project. In order for the radio button to function properly, I have to uncheck it and then recheck it. The pixel drawer allows me to change colors and sizes using these radio ...

Disabling the .hover function temporarily

I am currently exploring how to temporarily disable the .hover function in jQuery based on a specific event that occurs on the page. You can view my current jsfiddle here: http://jsfiddle.net/4vhajam3/3/ (please note that I have omitted some code for simp ...

Mastering the use of Action.Submit in adaptive cards to simulate user input

I am trying to implement MessageFactory.SuggestedActions within my "welcomeCard" adaptive card. Essentially, in my adaptive card (welcome card), I have several buttons for the user to click on, each with an Action.Submit type. { "type" ...

Retrieve the element (node) responsible for initiating the event

Is there a way to identify which element triggered the event currently being handled? In the following code snippet, event.target is only returning the innermost child node of #xScrollPane, with both event.currentTarget and event.fromElement being null. A ...

Combining numerous inputs into an array in a React component

As a beginner in coding, I am eager to learn React by building a project. Currently, I am facing a challenge and seeking guidance. https://i.sstatic.net/Ic2zC.png My goal is to store all these values in an array structured as follows: { option: { s ...

Typescript counterpart of a collection of key-value pairs with string keys and string values

Within the API I'm currently working with, the response utilizes a data type of List<KeyValuePair<string, string>> in C#. The structure appears as shown below: "MetaData": [ { "key": "Name", &q ...

AngularJS ng-switch-trigger enclosed within its own ng-switch-wrapper

In my current project, I am working on switching between two buttons that act as their own triggers for the switch. To illustrate further: <span ng-switch on="patientSwitch"> <span ng-switch-when="edit"> <button ng-click="patien ...