The for loop is decrementing the value instead of incrementing it

Hi there, I'm a beginner in JavaScript and I've been experimenting with it. Today, I encountered a problem that I need help with.

The code may seem messy but my goal here is to remove items from idList that are not found in onlinelike. However, I noticed that something was incorrect as the for loop meant to increment i like 0, 1, 2, etc. was actually counting down instead.

Please assist me with this issue.

const idList = ['group1 1', 'group2 2', 'group3 3', 'group1 4'];

const onlinelike = ['group1 1', 'group3 2', 'group2 3', 'group1 4'];

var RemovedList = [];

if (idList != null) {
  idList.forEach(item => {
    if (onlinelike != null) {
      for (i = 0; i < onlinelike.length; i++) {
        if (onlinelike[i].split(' ')[0] === item.split(' ')[0]) {
          if (onlinelike[i].split(' ')[1] !== item.split(' ')[1]) {
            console.log(item, 'to be removed')
            console.log(i);
         }
       }
     }
   });
}

By the way, when I removed an if statement from it, it started behaving even more oddly by counting like 0, 3, 2, 1, 0, 3.

const idList = ['group1 1', 'group2 2', 'group3 3', 'group1 4'];

const onlinelike = ['group1 1', 'group3 2', 'group2 3', 'group1 4'];

var RemovedList = [];

if (idList != null) {
  idList.forEach(item => {
    if (onlinelike != null) {
      for (i = 0; i < onlinelike.length; i++) {
        if (onlinelike[i].split(' ')[0] === item.split(' ')[0]) {
          console.log(item, 'to be removed')
          console.log(i);
        }
      }
    }
  });
}

Answer №1

To eliminate items from the idList that are not found in the onlinelike list, you can implement logic as shown below:

const idList = ['group1 1', 'group2 2', 'group3 3', 'group1 4'];

const onlinelike = ['group1 1', 'group3 2', 'group2 3', 'group1 4'];

idList.forEach((item) => {
  if(!onlinelike.includes(item)) {
    console.log(`Item to be removed ${item}`);
  }
})

If you prefer using utility libraries like lodash, the code can be further simplified for removing items from an array:

const idList = ['group1 1', 'group2 2', 'group3 3', 'group1 4'];
const onlinelike = ['group1 1', 'group3 2', 'group2 3', 'group1 4'];

_.remove(idList, (item) => !onlinelike.includes(item));

console.log(idList);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>

The function _.remove mentioned here is part of the lodash library.

Answer №2

Implementing .filter along with .includes()

const idList = ['group1 1', 'group2 2', 'group3 3', 'group1 4'];
const onlinelike = ['group1 1', 'group3 2', 'group2 3', 'group1 4'];

var RemovedList = idList.filter(item=> !onlinelike.includes(item))

console.log(RemovedList)

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

Leveraging environment variables in VueJS applications

Despite searching for solutions to my issue on different forums and websites, I have not been able to find a helpful answer. I am trying to utilize an API with Vue and need to account for the changing URL when the app is in production. To address this, I ...

When comparing the values of two arrays with undefined property values

Struggling with sorting an array of arrays that works perfectly except when the property value is undefined. Take this example: posts array = {id: "1", content: "test", "likes":[{"user_id":"2","user_name":"test"}] }, {id: "2", content: "test", "likes": ...

What is the best way to configure the time to T00:00:00.000Z in JS?

In my usage of ui-calendar, I am attempting to pass events without a specified time. Currently, I am retrieving the date and time in the following manner. var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); ...

An effective method for converting an array into an encoding suitable for ordinal regression analysis

Here is an array that I am working with: import numpy as np array = np.array([2, 3, 4]) I want to convert this array into the following format: [array([ 1., 1., 0., 0., 0.]), array([ 1., 1., 1., 0., 0.]), array([ 1., 1., 1., 1., 0.])] The c ...

React displaying incorrect data during array iteration

I have encountered a peculiar problem that I can't seem to find any information about online. If my issue has already been discussed elsewhere, I apologize for the duplicated query. The challenge revolves around managing a "Schedule" represented by a ...

Sending form data using Ajax in codeigniter

I am encountering an error while attempting to submit a form using ajax in codeIgniter. Below is the view code that I have: <div class="form-group input-control"> <p id="error1" style="display: none; color: green"><b>Registered Succ ...

Passing scope data to JSON in AngularJS involves converting the data from the

Hello, what is the best way to transfer $scope data to JSON during initialization? For example, I have a scope with users: $scope.users = [ { name: "Camila Gilson" }, { name: "Chloe Creighton" }, { name: "Zoey White" } ]; I am interested in storin ...

Having issues updating table with Javascript after form submit in IE and Edge browsers

My current setup involves using Contact Form 7 in Wordpress to store data in a MySQL Database with Submit-Form. Now, I am working on reloading a table containing this data after the form submission. Here is the script I am currently using: /* FORM RELOAD ...

Issue with accessing Scope value in AngularJS directive Scope

FIDDLE I've recently developed a directive that looks like this: return { restrict: 'EAC', scope: { statesActive: '=' }, link: function (scope, element, attrs) { var ...

The value of Req.params is currently not defined

I am currently dealing with the following code snippet: router.get('/invite/:invitecode', async(res,req) => { return console.log(req.params) if(!req.params.invitecode) { return res.render('404') } if(!req.user) { res. ...

What is the best way to combine a collection of strings and HTML elements in a React application?

I am facing a challenge with my list of names. I typically use .join to add commas between each name, but one specific item in the list needs to display an icon of a star next to it based on a certain condition. The issue is that using join turns everyth ...

Only submit the form if all files are selected to prevent any missing files from being uploaded

I am currently utilizing the Vue.js framework along with Axios. Within my HTML page, I have incorporated two separate input fields for selecting an image. Additionally, there is a form present on the page. It's important to note that these inputs and ...

Unlocking hidden gridview column values with the power of jQuery

Within my gridview control, there are 4 columns, with one column being invisible which contains the Email Address information. <asp:GridView id='gridData' runat='server'> <Columns> <asp:TemplateField> ...

Can you configure the redux store once and share it across different pages?

I have a redux store where the state is in the form of {names:[], address:[]}. Across multiple pages, both names and address are used as properties. However, I find myself making API calls on each page to fetch these values which is causing unnecessary n ...

Automating the deletion of an empty array from a MongoDB document using Java

Dealing with a MongoDB nested array can sometimes result in empty arrays remaining in the document after adding and removing elements. In the scenario where indexes 0 and 1 are removed from the "play" array, the goal is to have the "play" array removed ent ...

Tips for obtaining results from a File Reader

I am currently facing an issue with an onchange event in my HTML. The event is intended to retrieve an image from the user, convert it to a data URL, and then send it over socket.io to store in the database. However, I am struggling to figure out how to ac ...

How come my responsive design functions properly when I test it using the mobile device tool, but fails to work when I manually decrease the browser size?

While testing my responsive design, I've noticed that using the toggle device tool in the Inspect tools of my browser produces the expected results. However, when I simply resize the browser window manually, the design does not respond as it should. C ...

Utilizing AJAX to add information to jQuery data tables without taking advantage of their pagination and advanced features

The jQuery datatables plugin is a useful tool for adding filters, pagination, and search functionality to web applications. I have personally integrated it with my Laravel project to organize and display data effectively. Recently, I decided to enhance th ...

error when trying to bind attributes to knockout components

I am trying to dynamically add an id attribute to a tag, but it keeps giving me an error. "Uncaught ReferenceError: Unable to process binding "attr: function (){return {id:id} }" Message: id is not defined" Here is my HTML code- <label data-bind= ...

Check if the count of unique elements in the array is greater than

Is there a way to count instances where the customer_id exists more than once? I only want to count instances where the number appears more than once. $customerOrder = $this->Order->find('all', array( 'conditions&apo ...