Automatically adjusting maps according to internal criteria

I have an example of a map that looks like this

const Map = new Map().set('123', [ [ 'foo', 'bar' ] ]).set('456', [ [ 'baz', 'qux' ], [ 'quux', 'corge' ] ]);
/* 
The structure of the Map is as follows:
    Map {
       '123' => [ [ 'foo', 'bar' ] ],
       '456' => [ [ 'baz', 'qux' ], [ 'quux', 'corge' ] ] 
   } 
*/

If I wanted to delete the array where the first nested element equals 'quux', how would I achieve that in order to obtain the following result?

Map {
    '123' => [ [ 'foo', 'bar' ] ],
    '456' => [ [ 'baz', 'qux' ] ] 
}

I can easily remove the item using the following code:

Map.set('456', (Map.get('456')).filter(array => array[0] !== 'quux'));

However, this method only works because I know which key ('456') contains the element with value 'quux'. I am uncertain of how to programmatically search through the Map, identify the corresponding key, and then remove the item. The keys and values within the Map may vary dynamically, but the structure remains consistent. The search term will remain static, for instance: 'quux', meaning that while the contents of the Map may change, I am essentially conducting a search and removal process.

Answer №1

To find the desired value in a map, you can iterate through the map and filter out arrays based on certain conditions.

const myMap = new Map([['123', [['foo', 'bar']]], ['456', [['baz', 'qux'], ['quux', 'corge']]]]);

myMap.forEach((value, key, map) => {
    if (value.some(item => item[0] === 'quux')) {
        map.set(key, value.filter(item => item[0] !== 'quux'));
    }
});

console.log([...myMap]);

Answer №2

To iterate through the elements of a Map, you can utilize the findIndex method on each value v to check if it contains an array with 'quux' as its first element, and then remove that array using the splice function:

const map = new Map().set('123', [ [ 'foo', 'bar' ] ]).set('456', [ [ 'baz', 'qux' ], [ 'quux', 'corge' ] ]);

console.log("before", [...map]);

for (const v of map.values()) {
  const index = v.findIndex((a) => a[0] === "quux");
  
  if (index > -1) {
    v.splice(index, 1);
  }
}

console.log("after", [...map]);

For a non-destructive approach, you can create a new Map by extracting entries from the original one and filtering out unwanted arrays using the map and filter methods:

const before = new Map().set('123', [ [ 'foo', 'bar' ] ]).set('456', [ [ 'baz', 'qux' ], [ 'quux', 'corge' ] ]);

console.log("before", [...before]);

const after = new Map([...before].map(([k, v]) => {
  return [k, v.filter((a) => a[0] !== "quux")];
})

console.log("after", [...after]);

Please note: The main distinction between these two approaches is that the second one removes all arrays where 'quux' is the first element, while the first one only removes the first occurrence. You can modify them according to your specific requirements.

Answer №3

If you want to dynamically generate keys, consider using a for...of loop in your code:

Don't forget to open your devtools to view the new map as it may not display correctly in the code snippet.

const myMap = new Map().set('123', [
  ['foo', 'bar']
]).set('456', [
  ['baz', 'qux'],
  ['quux', 'corge']
]);

for (let keyVal of myMap) {
  myMap.set(keyVal[0], (myMap.get(keyVal[0])).filter(array => array[0] !== 'quux'));
}

console.log(myMap);

I hope this solution meets your requirements. Feel free to leave a comment if you need further assistance! ;)

Answer №4

To iterate through the key-value pairs of a map, we can access the outer array containing the inner arrays in order to filter out the specific value we're searching for. By using the forEach function, we can determine the index of the inner array and then utilize the splice function to remove it from the outer array.

const dataMap = new Map().set('123', [ [ 'foo', 'bar' ] ]).set('456', [ [ 'baz', 'qux' ], [ 'quux', 'corge' ] ]);
dataMap.forEach((value, key) => {
   value.forEach((array, index) => {
      if (array.includes('quux')) {
         value.splice(index, 1);
      }
   });
});
console.log(dataMap);

Answer №5

Should we always utilize Array.prototype.filter for better performance, or is it more efficient to first use Array.prototype.some before filtering the array?

In this scenario, the code filters all arrays without first checking for the presence of 'quux'.

const map = new Map().set('123', [ ['foo', 'bar' ] ]).set('456', [ [ 'baz', 'qux' ], [ 'quux', 'corge' ] ]);

map.forEach((val, key) => {
  val = val.filter(arr => arr[0] !== 'quux');
  map.set(key, val);
});

console.log(map);

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

Transforming a form containing recurring elements into JSON

Sorry if this topic has already been discussed, I wasn't able to locate any information I currently have an html form structured like so: <form> <div> First Name <input name="FirstName" type="text"> Age <input name="Age" t ...

Implementing a Radial Cursor with a Custom Background Image in JavaScript

I am attempting to implement a radial cursor on a website that features a background image. Currently, I am facing two main issues: The radial cursor works in Chrome but not in Firefox. When using Firefox, I encounter a parsing error related to the "bac ...

Tips for effectively managing loading and partial states during the execution of a GraphQL query with ApolloClient

I am currently developing a backend application that collects data from GraphQL endpoints using ApolloClient: const client = new ApolloClient({ uri: uri, link: new HttpLink({ uri: uri, fetch }), cache: new InMemoryCache({ addTypename: f ...

Transforming jquery code into Angularjs code

I am currently working on a jQuery method that adds a 'selected' class to table rows and handles click events. Here is the code: $('.niGridTable table tr').addClass('selected').end().click(function (event) { event = ...

Encountering difficulties when attempting to inject NotifierService into an Angular Service

I am attempting to incorporate Angular NotifierService into my service class so that I can display error notifications in case of any exceptions from the service side. I attempted to inject a bean of NotifierService in the constructor of my service class, ...

Is it possible to utilize $(this) within the $.post() function?

I seem to be having trouble accessing $(this) from inside the $.post section. It works perfectly fine outside of it. Here is the JavaScript code: $('.idea').each(function(){ var title = $(this).html(); $.post("votes.php", { t ...

Tips for distinguishing individual rows within a table that includes rowspans?

My Vue application calculates a table with rowspans by using an algorithm based on a configuration file. This allows the application to render columns (and maintain their order) dynamically, depending on the calculated result. For example, see the code sn ...

Having trouble retrieving information from the local API in React-Native

Currently, I have a web application built using React and an API developed in Laravel. Now, I am planning to create a mobile app that will also utilize the same API. However, I'm encountering an issue where I cannot fetch data due to receiving the err ...

Encountering difficulties in JavaScript while trying to instantiate Vue Router

After following the guide, I reached the point where creating a Vue instance was necessary (which seemed to work). However, it also required providing a Vue Router instance into the Vue constructor, as shown below. const router = new VueRouter({ routes }) ...

Tips for aligning pagination in the MUI v5 table component and creating a fixed column

I am currently experimenting with MUI table components and have created an example below with pagination. const MuiTable = () => { const [page, setPage] = useState(0); const [rowsPerPage, setRowsPerPage] = useState(5); const [data, setData] ...

What is the best way to assign a URL to an image source using a JavaScript variable?

I am working on a script that displays different image URLs based on the time of day using an if-else statement. I want to dynamically load these images in an img src tag so that a different picture is loaded for each time of day. I have defined variables ...

Points in an array being interpolated

I am currently working with data points that define the boundaries of a constellation. let boundaries = [ { ra: 344.46530375, dec: 35.1682358 }, { ra: 344.34285125, dec: 53.1680298 }, { ra: 351.45289375, ...

Trouble with minification in Sencha cmd 5

I've been attempting to compress a Sencha 5 project using Sencha CMD, but I keep experiencing failures. sencha generate app -ext demoApp ./demoApp Then, in an effort to compress the application, I entered the following command: sencha app build ...

Exclude a specific tag from a div in JavaScript

I need help selecting the text within an alert in JavaScript, excluding the <a> tag... <div id="addCompaniesModal" > <div class="alertBox costumAlertBox" style="display:inline-block;"> <div class="alert alert-block alert- ...

Is Nextjs the best choice for developing the frontend code exclusively?

When deciding whether to use Next.js or plain React for my front-end development, should I consider that a back-end already exists? If I am not planning to write a new back-end, which option would be better suited for the project? ...

Using JS regular expressions to only select anchor (a) tags with specific attributes

When trying to select a link tag (a) with a specific data-attr, I encountered an issue. I currently use the following regex pattern: /<a.*?data-extra-url=".*?<\/a>/g. However, I noticed that this selection goes wrong when there are no line br ...

How can I implement a for loop in Node.js?

I am currently experiencing an issue with my for loop while attempting to retrieve data from MongoDB and display it in the browser. The problem is that it only iterates through once, resulting in only the first entry being output. Strangely enough, when ...

Facing some unexpected issues with integrating Django and AngularJS, unclear on the cause

In my simple Angular application, I encountered an issue. When I run the HTML file on its own in the browser, the variable name "nothing" is displayed as expected. However, once I integrate the app into Django by creating a dummy view that simply calls a t ...

Struggling to create a BMI Calculator using JS, the result is consistently displaying as 'NaN'

Having trouble creating a BMI Calculator using JavaScript. The issue I'm facing is that the calculation always returns 'NaN'. I've tried using parseInt(), parseFloat(), and Number() but couldn't solve the problem. It seems that the ...

Secure the data by encrypting it in the frontend before decrypting it in the

How can I achieve the highest level of security in this situation? I have experimented with using the same public key for all users to encrypt data transmitted over HTTPS to my backend automatically. However, individuals could potentially intercept and d ...