The function executes one loop and then outputs the result

This function is designed to remove duplicate items from an array:

removeDuplicates(item: String, allForToday: Array) {
    let temp = allForToday;
    for (let i = 0; i < temp.length; i++) {
        if (temp[i].indexOf(item) > -1) {
            temp = temp.splice(i, 1);
        }
    }
    return temp;
}

To use this function, you would call it like this:

for (let i = 0; i < lastWeekItems.length; i++) {
                allForToday = t.removeDuplicates(lastWeekItems[i], allForToday);
 }

The parameter lastweekItems[i] is a string, and allForToday is an array of strings in the format: 1;2;3. For example, lastweekItems[i] could be 2. The expected behavior is for the entire array to be checked for each item, removing any occurrences found. However, the observed behavior is that only temp[0] is checked, leading to the entire remaining portion of the array being spliced, resulting in an empty array (temp.length changes from 14 to 1)...

Answer №1

If you're looking to eliminate any duplicates from an array, consider using a reducer function like the one shown below:

let numbers = [1, 2, 3, 4, 5, 5, 4, 3, 2, 1];

let uniqueNumbers = numbers.reduce(function(acc, num) {
  if(acc.indexOf(num) === -1) {
    acc.push(num);
  }
  return acc;
}, []);

console.log(uniqueNumbers);

The 'uniqueNumbers' array will now only contain the distinct values from the original array.

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 exceljs function for downloading an Excel workbook is not activated by using the Post method

Presently, I am engaged in the development of a React and Node application. This app is designed to store data entries in a database, with the capability for users to download all stored data in an Excel workbook. To make this possible, I have integrated ...

After adding on, do you wish to eliminate?

I have implemented zoom buttons on my Map container However, I need to hide these zoom buttons when a specific map image is displayed Code: JS: Map = function() { //private: var $MapContainer; this.initMap = function($container, zoomHidden) { $Map ...

Beginners guide to initializing a character array within a struct

What is the correct way to initialize a character array in a C# structure? I am trying this: struct cell { public char[] domain = new char[16]; public int[] Peers; public int NumberOfPeers; public char assignValue; } However, I am receivi ...

What is the best way to programmatically insert a new element into the DOM after it has already been rendered in Next

In my project with Next.JS 13, I am currently exploring methods to manually inject component code into an existing element in the DOM that has already been rendered. Below is the code snippet for the component: const layouts = { forgotPassword: () => ...

Browser randomly cancels Ajax calls without displaying any error messages

For my project using PHP with Symfony 2, I incorporate numerous Ajax requests on each page. However, I've been encountering issues as it seems like browsers such as Google Chrome and Firefox are abruptly aborting these requests without any clear error ...

Is there a way to transfer a JSON array from a text/javascript block to a runat=server block within the context of ExactTarget/Salesforce Marketing Cloud?

I have a page containing two <script> elements: one is running locally and the other one is running on the ExactTarget server: <script type="text/javascript"> var results = localStorage.getItem('results'); var results = JSON.parse(re ...

Issue: The Material-UI DataGrid Column Filter is not compatible with Material-UI Dialog

I am currently facing an issue with my Material-UI DataGrid in React JS. I have successfully integrated the table inside a Material-UI DialogContent and everything seems to be working fine - ordering, renderCells, checkboxSelection, etc. However, I am enco ...

A for loop is executed after a console.log statement, even though it appears earlier in the code

When this specific block of code is implemented var holder = []; const compile = () =>{ let latitude = 0; let longitude = 0; for (let i = 0; i < holder.length; i++) { Geocode.fromAddress(holder[i].city).then( (response ...

Issue with Amcharts: Category data not displayed when cursor is altered

I recently came across some examples by Amstock (1,2) where the category field block is enabled when moving a cursor. Despite my efforts, I couldn't replicate this functionality in my project. Here are my current chartCursorSettings: this.chart ...

A step-by-step guide on efficiently connecting multiple arrays of data imported from Excel in Laravel using PHP

After successfully importing excel data into my database using a different code than usual, I encountered an issue with attaching relationships. The database consists of three tables: users (1st table), role_user (relationship table), and roles (2nd table ...

The 'getAllByRole' property is not found in the 'Screen' type. TS2339 error

I am currently developing a web application using ReactJs for the front end. While testing the code, I encountered the following error: TypeScript error in My_project/src/unitTestUtils.tsx(79,27): Property 'getAllByRole' does not exist on type & ...

Upon clicking outside of the input field, ensure that there is a space added to the

I have these input boxes where integers are entered. My goal is to display them similar to the images below: 1: https://i.sstatic.net/3HUbO.png 2: https://i.sstatic.net/4722H.png $(document).ready(function() { $("input").each(function() { $(th ...

An array containing concatenated values should be transferred to the children of the corresponding value

Consider this example with an array: "items": [ { "value": "10", "label": "LIMEIRA", "children": [] }, { "value": "10-3", "label": "RECEBIMENTO", ...

Is there a way to stop a setInterval function that is running using a global variable?

I've been trying to figure out how to stop a running setInterval, but despite making changes based on various resources, I still can't seem to get it to stop. Currently, I have implemented a Mutation Observer that detects a class change. Once th ...

Learn how to implement scrolling text using JavaScript and jQuery, where text slides by clicking on the previous and next icons

click here to see the image Is it possible to create a text slider that moves when clicking on previous and next icons? I want only 10 texts to be visible at a time, with the rest hidden. When clicked, all the texts should appear. Unfortunately, I don&apo ...

How can I calculate the year difference between dates using Moment.js?

Hello, I need help with finding the difference between two dates using Moment.js. Below is my code: https://jsfiddle.net/FLhpq/6082/ let secondDate = "2019-12-01"; // format YYYY-MM-DD; let day = moment().format('YYYY-MM-DD'); // calculate the ...

What steps should I take to verify the validity of an Angular form?

I am struggling with validating an inscription form in HTML. Despite trying to implement validations, the inputs are still being saved in the database even when they are empty. Here are the validations I want to include: All inputs are required Email addr ...

encountering challenges while creating a multi-step registration form with Node.js, Express, and mongoDB

I'm currently working on a 3-page registration form that saves data using MongoDB. However, I encountered an issue where the collection "detail" only stores one user's data at a time due to the structure of my post requests across all pages. I ne ...

Choose a paragraph of text that spans multiple lines without exceeding the width

In the image above, the red selection crosses outside of the yellow area when selecting. I would like to only select within the yellow part as shown below: Here is the HTML: <div id="parent"> <div id="child"> This is some content. ...

Enrolling a new plugin into a software repository

I have 5 unique classes: ConfigManager ForestGenerator TreeCreator NodeModifier CustomPlugin My goal is to create an npm module using TypeScript that incorporates these classes. The main feature I want to implement is within the ConfigManager clas ...