Removing an element from an array by evaluating each item within the array

Input array:

["temp/1/Lounge/empty", "temp/1/Lounge/66,66,66,66,66,66,66,66,64,64,64,64…,64,64,64,64,64,64,64", "temp/2/Lounge/empty", "temp/3/Lounge/empty"]

I have a list of elements like the above. Each element consists of four parts separated by slashes ('/'). If the first three parts are identical and the fourth part is different for any two elements, I need to remove the one with 'empty' as the fourth part.

For example: If one item has 'empty' as the fourth part and another item has data like 66,64,...,64,64,64 as the fourth part, I should eliminate the one with 'empty' as the fourth part in the array.

The desired output should be:

["temp/1/Lounge/66,66,66,66,66,66,66,66,64,64,64,64…,64,64,64,64,64,64,64", "temp/2/Lounge/empty", "temp/3/Lounge/empty"]

I attempted to split the items in the array:

for(i=0;i<arr.length;i++){
   stringType = message.split('/')[0];
   day = message.split('/')[1] ; //day
   room = message.split('/')[2] ; 
   settingData = message.split('/')[3] ;
}

Please assist me in comparing the elements and removing them from the array.

Answer №1

If you want to achieve this, follow these steps:

  • Begin by storing in a hash map the "4th values" for each array value;
  • Then, filter the array and remove any array values where the 4th value is empty but there are other 4th values present (this can be checked using the created hash map).

function splitValue(value, ignoreCase) {
  let split = value.split('/'),
      key = split.slice(0, 3).join('/'),
      val = split.slice(3).join('/');
  if (ignoreCase) {
    key = key.toLowerCase();
  }
  return [key, val];
}

function filter(arr, ignoreCase = false) {
  var byKey = {};
  for (let value of arr) {
    let [key, val] = splitValue(value, ignoreCase);
    if (!byKey.hasOwnProperty(key)) {
      byKey[key] = [];
    }
    if (val !== 'empty') {
      byKey[key].push(val);
    }
  }
  return arr.filter((value) => {
    let [key, val] = splitValue(value, ignoreCase);
    return (val !== 'empty' || byKey[key].length === 0);
  });
}

console.log(filter([
  "temp/1/Lounge/empty",
  "temp/1/Lounge/something",
  "temp/2/Lounge/empty",
  "temp/3/Lounge/empty"]));

console.log(filter([
  "temp/1/Lounge/something",
  "temp/3/kitchen/something",
  "temp/1/Lounge/empty",
  "temp/3/Kitchen/empty"]));

console.log(filter([
  "temp/1/Lounge/something",
  "temp/3/kitchen/something",
  "temp/1/Lounge/empty",
  "temp/3/Kitchen/empty"], true));
.as-console-wrapper {
  max-height: 100% !important;
}

The example above also illustrates how you can ignore letter casing, treating temp/3/kitchen/... and temp/3/Kitchen/... as part of the same group.

Answer №2

This piece of code will suit your needs perfectly.

var resultData = ["temp/1/Lounge/empty", "temp/1/Lounge/66,66,66,66,66,66,66,66,64,64,64,64…,64,64,64,64,64,64,64", "temp/2/Lounge/empty","temp/3/Lounge/empty"];
var data = resultData;
for(var i=0; i<data.length; i++){
   var iItem = data[i];
   var iFirst = iItem.substring(0, iItem.lastIndexOf("/") + 1);
   var iLast = iItem.substring(iItem.lastIndexOf("/") + 1, iItem.length);
   for(j=i+1 ; j<data.length; j++){
       var jItem = data[j];
       var jFirst = jItem.substring(0, jItem.lastIndexOf("/") + 1);
       var jLast = jItem.substring(jItem.lastIndexOf("/") + 1, jItem.length);
       if(iFirst === jFirst && iLast==='empty'){
          resultData.splice(i,1);
       }
   }
}
console.log(resultData);

The data array is an exact replica of the resultData array to ensure a proper loop when elements are removed from them. For more experimenting with the lengthy array values, you can refer to this functional JSFIDDLE link.

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 array used within the useEffect hook and the getCoordinates function appears to be distinct when printed with console

Utilizing GoogleMap API for Custom Location Display I have an imported array of JSON objects named data which includes an address property. The Google Maps API is used to retrieve coordinates from the addresses in order to generate custom markers displaye ...

The #each helper in Handlebars is used to iterate over an array

I have a function that generates an array as output. I am looking for a way to iterate over this array using the each method. Can anyone provide guidance on how to achieve this? Consider if the handlebars helper produces the following array: details: [{ ...

standards for matching patterns (such as .gitignore)

Throughout my experience, I have utilized various tools designed to search a codebase for specific files and then carry out operations on those files. One example is test libraries that identify all the necessary files for execution. Another common tool is ...

"Is there a way to retrieve the props that have been passed down to a

I am looking to have custom props created in the root layer of my React app: import React from 'react' import App, { Container } from 'next/app' export default class MyApp extends App { static async getInitialProps({ Component, rout ...

Require assistance with refreshing the index for the chosen row

I have encountered a problem while attempting to manipulate table rows using Javascript. Adding new rows works fine, but deleting rows presents an issue. Specifically, the delete function fails if the first row or a row in the middle is deleted (the live ...

Utilizing inter-process communication in Electron to establish a global variable from the renderer process

renderer.js ipcRenderer.sendSync('setGlobal', 'globalVarName').varInner.varInner2 = 'result'; main.js global.globalVarName = { varInner: { varInner2: '' }, iWontChange: ' ...

Utilizing internal PDF links in a Microsoft UWP application

In the process of developing a UWP app using javascript, I have created a list of links that are connected to PDF files stored locally in the app. The ultimate goal is to offer a collection of hands-free documentation for the Hololens (Windows AR) device. ...

The parent component is failing to pass the form values to the child form group in CVA

My Angular application (view source code on Stackblitz) is running Angular 15, and it utilizes reactive forms along with a ControlValueAccessor pattern to construct a parent form containing child form groups. However, I am encountering an issue where the d ...

What is the best way to retrieve the array of triangles used to construct the 3D object?

I am trying to retrieve the array of triangles from the geometry object, but I am having trouble locating it. It seems that .faces in the object are not actually triangles. For example, when creating a cube, a face is structured like this: "faces": [{ ...

What sets apart a React component from a function-as-component in React?

React is really confusing to me right now. Take this simple react component for example: export default function Foo(){ return( <div> <div>some text</div> </div> ) } I want to add a child compone ...

How to Transform JSON Element into a JavaScript Array in AngularJS?

Implementing AngularJS to fetch values in JSON format using $resource call. The model element I require is a Javascript array structured as: [ [1328983200000, 40], [1328983200000, 33], [1328983200000, 25], [1328983200000, 54], [1328983200000, 26], [1328 ...

Exploring the potential of utilizing the "wait" function in Selenium WebDriver for

I want to automate a test on my website using the Selenium WebDriver for JavaScript. How can I approach running tests here with content that may not be ready when the page loads, such as data coming from an external API? In my case, the content is loaded ...

Executing a JavaScript code in a Python webdriver: A step-by-step guide

Using Selenium 2 Python webdriver: I encountered an issue where I needed to click on a hidden element due to a hover effect. In search of solutions to unhide and select the element, I came across the following examples: Example in Java: JavascriptExecut ...

When an answer is provided in Inquirer.js, pressing Enter is causing the process to terminate

Currently, I am working on creating a Command Line Interface (CLI) using the NPM package called Inquirer. It has been a useful tool so far, but I have encountered an issue. The interface functions correctly in terms of posing questions to the user, but onc ...

Struggle with incorporating a file

As part of the login process, I have two options available: easy login and standard login. The easy login requires an employee ID, birthdate, and captcha answer, while the standard login asks for first name, last name, birthdate, and captcha. To facilitate ...

Executing Javascript dynamically in VueJS: Learn how to run code from a string efficiently

Currently, I am developing a website with VueJS that enables selected users to upload scripts for automatic execution upon page load. For instance, here is an example of the type of script a user may input: <script src="https://cdnjs.cloudflare.com/aja ...

Tips for triggering useEffect just once when various dependencies are updated simultaneously

Currently, I have implemented a useEffect hook with two dependencies in the following way: useEffect(() => { ..... }, [apiData, currentMeasurements]); It's important to note that the apiData is fetched using useLazyQuery from apollo/client. Upon ...

Is there a way to connect and interact with a different ng-controller's ng-model within a separate ng-controller?

Is it possible to access the ng-model from another ng-controller and if so, how can it be done? In this scenario, I am using two controllers. The first controller has a model called mddl1, while the second controller does not have any other model. However, ...

The functionality of minified JS code is limited to being copied and pasted directly into the

Trying to explain the issue I'm facing may be a bit tricky, but here it goes: I've been working on an AngularJS app (not live yet) and we felt the need to add tooltips for specific metrics in our tables. After some research, we really liked the ...

Stop the unnecessary reloading of Ajax data when navigating back using the browser's back button in Chrome and Internet Explorer

I am currently designing a website where the main page showcases the latest 10 blog entries. As I scroll down and approach the end of the last item on the screen, another set of 10 blog entries automatically load through infinite scrolling. If a user clic ...