Removing repetitive strings from an array in the most efficient manner

We've successfully developed a script to eliminate duplicate strings from an array while preserving the order necessary for angular's ng-repeat loop. It's also important that the remaining elements maintain their original index.

scope.feedback = _.map(_.pluck(item.possibleAnswers, 'feedback'), function (element, index, collection) {
    return collection.slice(0, index).indexOf(element) === -1 ? element : '';
});

Although this code is functional, we can't help but think there may be a simpler solution out there. Has anyone encountered a similar issue and found a more straightforward workaround?

Answer №1

In case the browsers you are targeting have compatibility with the spread operator, you can test it in your console by running:

[...new Set(['3','1','1','5'])]
// ['3','1','5']

Alternatively, if the browser supports Array.from, you could use the following code as well:

Array.from(new Set(['3','1','1','5']))
// ['3','1','5']

Answer №2

Here is a different approach using the reduce method https://jsfiddle.net/58z7nrfy/1/

var numbers = [1,2,3,1,2,3,2,2,3,4,5,5,12,1,23,4,1];

var uniqueNumbers = numbers.reduce(function(previousValue, currentValue, index, array){
  if (previousValue.indexOf(currentValue) == -1) 
    previousValue.push(currentValue);
  else 
    previousValue.push('');
  
  return previousValue;
}, [])
console.log(uniqueNumbers)

[1, 2, 3, "", "", "", "", "", "", 4, 5, "", 12, "", 23, "", ""]

Answer №3

In addition to previously mentioned solutions, an alternative method is utilizing the lodash union function in the following manner:

const duplicates = ['Apple', 'Banana', 'Apple'];
const uniques = _.union(duplicates);

The unique values will be: ["Apple", "Banana"]

Answer №4

To optimize your code, consider utilizing a Map. This data structure is type-safe and avoids repetitive iterations using Array#indexOf.

var array = [1, 2, 3, 1, 2, 3, 2, 2, 3, 4, 5, 5, 12, 1, 23, 4, 1, '23'],
    uniqueValues = array.filter(function (value) {
        if (!this.has(value)) {
            this.set(value, true);
            return true;
        }
    }, new Map);

console.log(uniqueValues);

Answer №5

The current accepted answer may not be the most efficient solution. Utilizing reduce in conjunction with a hash table or map object could greatly enhance performance. In my opinion, using a map instead of reduce would be preferable. Expanding on @Nina Scholz's method by utilizing double maps, the optimal response to the original poster's question is as follows;

var   a = [1, 2, 3, 1, 2, 3, 2, 2, 3, 4, 5, 5, 12, 1, 23, 4, 1, '23'],
unified = a.map(function(e) {
                  return this.has(e) ? void 0 : (this.set(e,"Cheap Thrills"),e);
                }, new Map());
console.log(unified);

If this were to be used in a production environment with an array of arbitrary length, I would opt for implementing the map method with standard functions rather than functors. This approach can introduce a significant performance boost when dealing with large arrays, especially those exceeding a size of 10K+

Answer №6

I find the lodash method uniq() to be incredibly useful

let numbers = [1, 2, 3, 1, 2, 3, 2, 2, 3, 4, 5, 5, 12, 1, 23, 4, 1];
let uniqueNumbers = _.uniq(numbers, (element) => {
 return element;
});

The resulting output is:

[1, 2, 3, 4, 5, 12, 23]

Answer №7

Here is the script that I incorporated:

const uniqueWords = ['alpha', 'beta', 'gamma', 'gamma', 'delta', 'beta'];
    const finalResult = [];
    for(let j=0; j<uniqueWords.length; j++){
      if(finalResult.indexOf(uniqueWords[j]) == -1){
        finalResult.push(uniqueWords[j])
      }
    }

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

Utilize JavaScript to communicate with the backend server

I'm embarking on my first Cordova application, utilizing HTML, CSS, and JavaScript. My current objective is to trigger a local server call upon button click, with the intention of logging something to confirm functionality. However, I'm encounter ...

Tips for making a background image responsive using ng-style in AngularJS

Can anyone assist me in fixing the gap space issue in a responsive view with an attached jpg background image? Follow this link for more details: enter image description here ...

Guide for accessing and interpreting a random folder arrangement using JavaScript located alongside index.html

I am currently developing a testing reporting tool that organizes images into folders, resulting in a structure similar to this: root/ /counter/ img1.png img2.png /alarm/ img3.png The names of the folders like counter and alarm are not f ...

Traverse an array containing nested objects using Javascript

I am facing difficulty printing out objects stored in an array. When I console log, this is the result: console.log(product.categories) https://i.stack.imgur.com/YVprQ.png How can I iterate through these nested objects to display them individually like t ...

Creating these three functions directly in the Parent Component instead of duplicating code in the child component - ReactJS

I am new to React and currently working on a dashboard page that includes a React Table. The page features a customize button that opens a popup with checkboxes to show/hide columns in the table. By default, all checkboxes are checked but unchecking a colu ...

Navigating with Link in React Router DOM v5 to successfully pass and catch data

In the process of developing a basic chat application, I encountered an issue with passing the username via the Link component. Below is the relevant code snippet: <Link to={{ pathname: `/${room}`, state: { the: user } }}> Enter room </Link> ...

How to efficiently use promises within loops in JavaScript

I recently delved into Javascript and I'm still struggling with how promises work within loops. Currently, I am utilizing repl.it db for my project. Let's say I have an array consisting of keys, and my goal is to query each key in the array to st ...

Using the ng-repeat directive along with the string replace expression allows for dynamically

Struggling to find a way to remove a substring within an angular expression while using the ng-repeat directive. The controller resides in an external JavaScript file, and here is the corresponding HTML code snippet. function myController($scope, $http ...

Tips for adding values to an object

Behold, a complex object in multiple dimensions: let b = {} b.push({hello:'xyz'}) This method is currently inactive ...

Inability to input text into a textbox with AngularJS

I am currently working on developing an AngularJS app. I have encountered a problem where I am unable to input text into a textbox. The issue lies with my zoomService which handles zoom increments and decrements. While the user can zoom using a slider and ...

`There is a delay in rendering the background image on Chrome`

Once I apply a class to my button element using JavaScript, the background image (.gif) that is supposed to display afterwards takes an unusually long time to render. The button serves as a form submission. Upon being clicked, a class of "clicked" is dyna ...

Seeking advice on removing the initial blank space from a dropdown value in Angular.js

I have a deeply thought-out logic that I would like to illustrate with an example. However, in order to present it effectively, I am looking for suggestions on how to simplify the process without relying too heavily on the controller. <select class="fo ...

What is the method for tallying CSS page breaks in printed HTML documents?

Currently, for my report generation process using HTML and CSS to manage page breaks dynamically. I've enabled the option for users to print multiple reports at once by combining them into different sections within a single HTML document. This helps p ...

Executing Multiple Requests Concurrently in Angular 5 using forkJoin Technique

Important Note The issue lies in the backend, not Angular. The requests are correct. In my Angular5 app, I am trying to upload multiple files at once using rxjs forkJoin. I store the requests in an array as shown in the code below. However, after adding ...

Execute a function using a click event within a statement

Is it possible to trigger a function with parameters based on the result of a statement? For example, can we achieve something like this: (click)="datavalue.elementDataCollection.length > 1 ? AddNewDialog (datavalue,datavalue.COCLabel,mainindex,i) : r ...

Prevent the beforeunload dialog box from appearing

Looking for a solution that is compatible with all browsers and operating systems. Referring to this resource https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload This is what I have so far: window.addEventListener("beforeunload", function ( ...

The Angular Http Interceptor is failing to trigger a new request after refreshing the token

In my project, I implemented an HTTP interceptor that manages access token refreshing. If a user's access token expires and the request receives a 401 error, this function is designed to handle the situation by refreshing the token and re-executing ...

Hide all the div elements on the web page and only display one when a button is clicked

I have successfully set up a few buttons that can show and hide divs on click. However, I am wondering if it is possible to hide all other divs when one is showing, and also have "divone" show up on load. Buttons: <button class="btn btn-outline-primar ...

Verifying the content of the JSON data

If I receive JSON data that looks like this: {"d":1} Is it possible to determine whether the value after "d": is a 1 or a 0? I attempted the following method, but it always goes to the else block, even though I know the JSON data contains a 1. success: ...

Transferring information between AngularJS and Express/Node without using AJAX

My application is built using AngularJS on a node/express backend, with user authentication handled by passport. After a user signs in or signs up, the communication between my Angular controllers and express is done through $http ajax/xhr calls. The form ...