Splice, pop, shift, and read - the dynamic quart

When creating an array, I start by finding all the members in the chatbox:

var membersList = $('#chatbox_members' , avacweb_chat.doc.body).find('li');
var onlineUsers = [];
var offLineUsers = [];
for(var i =0;i<membersList.length;i++){
    var name = $(membersList[i]).text().replace("@","");
    onlineUsers.push(name);
}
alert(onlineUsers);

The resulting onlineUsers array would look something like this:

[Mr.EasyBB,Tonight,Tomorrow,Gone];

My question arises when using two for loops, one inside a setInterval function and another outside to compare:

var membersList = $('#chatbox_members' , _chat.doc.body).find('li');
var onlineUsers = [];
var offLineUsers= [];
for(var i =0;i<membersList.length;i++){
    var name = $(membersList[i]).text().replace("@","");
    onlineUsers.push(name);
}
var int = setInterval(function() {
    var newMember = ('#chatbox_members' , _chat.doc.body).find('li');
    for(var i =0;i<newMember.length;i++){
        var name = $(newMember[i]).text().replace("@","");
        offLineUsers.push(name);
    }

This results in:

onlineUsers = [Mr.EasyBB,Tonight,Tomorrow,Gone];
offLineUsers =  [Mr.EasyBB,Tonight];

In order to get the offline users, I want to replace onlineUsers with offLineUsers, which should return Tomorrow,Gone. However, since objects do not have a 'replace' function, how can I achieve this?

I suspect that using the splice function won't work without parameters, and methods such as pop or shift only remove elements from the beginning and end of an array.

Answer №1

for loop through offline users to check for matches with online users and remove them from the online users list.

Give this code a try.

Answer №2

It seems like I have grasped the concept correctly, here is a suggestion:

function eliminateDuplicates() {
  for (var i = 0; i < offlineUsers.length; i++) {
      onlineUsers.splice(onlineUsers.indexOf(offlineUsers[i]), 1);
  }
  offlineUsers = [];
}

Answer №3

If you're searching for a solution that works on modern browsers, you can use the array.filter method.

var onlineUsers = ["Mr.EasyBB", "Tonight", "Tomorrow", "Gone"];
var offLineUsers = ["Mr.EasyBB", "Tonight"];

function discord(online, offline) {
    return online.filter(function (element) {
        return offline.indexOf(element) === -1;
    });
}

console.log(discord(onlineUsers, offLineUsers));

Here is the output:

["Tomorrow", "Gone"]

You can test it on jsfiddle.

If you need the difference between arrays regardless of their order, you can try this approach:

var onlineUsers = ["Mr.EasyBB", "Tonight", "Tomorrow", "Gone"];
var offLineUsers = ["Mr.EasyBB", "Tonight"];

function difference(array1, array2) {
    var a = array1.filter(function (element) {
        return array2.indexOf(element) === -1;
    });

    var b = array2.filter(function (element) {
        return array1.indexOf(element) === -1;
    });

    return a.concat(b);
}

console.log(difference(onlineUsers, offLineUsers));
console.log(difference(offLineUsers, onlineUsers));

Outputs will be:

["Tomorrow", "Gone"] 
["Tomorrow", "Gone"] 

You can also check it out on jsfiddle.

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

Encountered an issue with mapping data from a controller to a view in Angular.js

Currently, my application consists of only three small parts: a service that makes an http call to a .json file, a controller that receives data from the service and sends it to a view. Everything was working fine when I hard coded the data in my service. ...

The responsive navigation menu expands

Struggling with my responsive menu issue here. I must admit, I am not a coding expert by any means, but I've been tasked with web design responsibilities at work. The problem at hand is that the website isn't fully responsive, except for the "ar ...

Managing onChange in a ReactJs project

Currently, my React tsx page features input boxes like the following: <textarea value={this.state.myData!.valueOne} onChange={(e) => this.handleValueOneChange(e)}/> <textarea value={this.state.myData!.valueTwo} onChange={(e) => thi ...

incapable of destructuring two objects simultaneously

Is there a way to map movies using columns as a property reference? For example: {movies.map(item => {columns.map(column => item.column.path)})} When I try this, the result is always undefined. The 'movies' array contains detailed inform ...

Using JavaScript, a checkbox can be employed to insert text into a textarea

I have a simple Javascript task that I'm trying to accomplish without using JQuery. My goal is to toggle the text in a textarea based on the state of a checkbox. When the checkbox is unchecked, I want the textarea to display "Hello", and when it' ...

Changing the default yarn registry for a specific project

Typically, I fetch packages from the internal server by using the command: yarn config set registry http://custom-packages-server.com However, for a new project, I want to switch back to the default registry without affecting other projects. If I try cha ...

Obtaining req.body twice while handling a 307 redirect in an Express application

I have encountered a unique issue with my form submission in an express js application. Upon form submission, data is being POST to another route and then redirected back to the original route. View <form action="action" method="post> <input t ...

I'm having trouble getting the activeStyle to work properly with a <NavLink>

I'm facing an issue with setting activeStyle for the NavLink component when the URL is on the map route. Currently, when I click on a NavLink, I can navigate to the correct route, but only <NavLink to='/' is being highlighted as active. ...

TypeScript is unaware that a component receives a necessary prop from a Higher Order Component (HOC)

My component export is wrapped with a higher-order component (HOC) that adds a required prop to it, but TypeScript seems unaware that this prop has already been added by the HOC. Here's the Component: import * as React from "react"; import { withTex ...

The endpoint 'pusher/auth' returned a 404 error code indicating that it was

I'm currently setting up a private channel using Pusher on a local node.js server. Strangely, I'm encountering a 404 error with my auth endpoint. Initially, I suspected a problem with how I defined the endpoint in relation to the local server&ap ...

Blend the power of Dynamic classes with data binders in Vue.js

Recently, I've been working on a v-for loop in HTML that looks like this: <ul v-for="(item, index) in openweathermap.list"> <li>{{item.dt_txt}}</li> <li>{{item.weather[0].description}}</li> <li>{{item.w ...

JQuery's addClass function is not functioning properly

Check out the code snippet below: function toggleAccessRequests() { var buttonValue = $("#showAccessRequests").val(); if (buttonValue == "Show") { $(".hideAccessRequest").removeClass("hideAccessRequest"); $("#showAccessRequests").v ...

Just hide the deleted message with a slideUp animation

I have implemented a PM system with a delete-message feature. The form I created checks for the message_id and message_title, posts to delete_message.php page, and deletes the message without refreshing the page through Javascript. There are two functions ...

GraphQL/Relay Schema "Field cannot be queried..."

I'm encountering an issue when trying to query specific fields in graphql/relay. My goal is to retrieve the "courseName" field for Courses from the schema provided below. For instance, if I query the User with: { user(id:1){firstname,lastname}} T ...

Issue: Your current version of `create-react-app` is outdated, version 5.0.0 is behind the latest release (5.0.1)

I'm having trouble running create-react-app as the title suggests. The version I am currently running, `create-react-app` 5.0.0, is outdated compared to the latest release (5.0.1). Global installation of Create React App is no longer supported. To f ...

Collect data entered into the input box and store them in an array for the purpose of

I need assistance with a code that involves input boxes for users to enter numerical values, which are then stored in an array. My goal is to add these values together and display the sum using an alert when a button is clicked. However, I am struggling to ...

Ways to acquire ttf files from a third-party domain without encountering CORS issues

I am attempting to obtain a .ttf file from an external website for use in my web application. However, when I try the following code: @font-face { font-family: 'font'; src: url('http://xxx.xyz/resources/tipografias/font.ttf') forma ...

Recommendation: 3 options for radio buttons on the registration form

My form includes a section where users need to choose if they want to sign up for a session that occurs 3 times daily. The catch is, only 5 applicants can enroll in each session (AM, Mid-day, PM). It's a competition to secure a spot. Here is the form ...

Difficulty with Angular's Interpolation and incorporating elements

I've encountered an issue with String Interpolation while following an Angular course. In my server.component.ts file, I've implemented the same code as shown by the teacher in the course: import { Component } from "@angular/core"; @Component ( ...

Accessing a frame inside an iframe using jQuery once the frame has fully loaded

Looking to access an element within a frame using jQuery. Here is the structure: <iframe id="frame1"> <frameset id="frameset"> <frame id="frame2"> <div id="exampleDiv">text</div> </frame> </frameset> < ...