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

Join the geomarkers in two datasets using connecting lines

I am currently developing a leaflet.js map incorporating two distinct sets of JSON data layers stored as js-files. The first dataset comprises the geographical locations of various newsrooms along with their respective IDs, while the second dataset contai ...

Storing dictionary<string,int> in a document

After not using C++ for a while, I found myself dealing with pointers and maps. Now, I have a string int map that I need to save to a txt file. int SaveMapToFile(string filename, map<string, int>* myMap) { int count = 0; if (myMap->empty() ...

What could be causing my search function to not recognize special characters?

It seems like there might be an issue with character encoding. My JavaScript search function is unable to identify specific strings that contain certain special characters such as parentheses, asterisks, and numbers. The JavaScript code I am using is quit ...

Encountering 404 errors when reloading routes on an Angular Azure static web app

After deploying my Angular app on Azure static web app, I encountered an error. Whenever I try to redirect to certain routes, it returns a 404 error. However, if I navigate from one route to another within the app, everything works fine. I have attempted t ...

Localization of date picker in material-table(Material UI)

Does anyone have experience with localizing the date picker in material-table (Material UI)? The date picker is specifically used for filtering in this scenario. import React from 'react'; import MaterialTable from 'material-table'; fu ...

Struggling to properly parse JSON data using jQuery

I am a beginner in jquery and have a php script that returns JSON data. However, I am facing an issue while trying to fetch and process the result using jquery. Below is the code snippet: calculate: function(me, answer, res_id, soulmates) { conso ...

Having difficulty implementing interval to a maximum of 2 minutes or until a certain condition is fulfilled in Angular

In my current scenario, I am working with two APIs - apiOne and apiTwo. When I call apiOne, it should return a response. If the response is successful, then I need to pass this response as a parameter to apiTwo. ApiTwo will then provide another response wh ...

Handling Errors in Asynchronous Functions with JavaScriptLet's explore the best practices for

I am a beginner in javascript and recently delved into async/await. After going through various resources, I gained a basic understanding. However, while experimenting with some code examples, I encountered unexpected results which left me puzzled about wh ...

How can I invoke a PHP script using AJAX?

I am currently working on implementing a feature that involves multiple tables where users can move table rows between the tables. I want to use ajax to call a php script that will update the database with the new values, specifically assigning a new paren ...

Creating a JSON object in JavaScript using an array

Can anyone assist me with the following code snippet for formatting the current month? var monthNames = ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set&apos ...

Retrieve the file name from the URL while disregarding the query string

Looking for a way to extract the test.jsp from this URL: http://www.xyz.com/a/test.jsp?a=b&c=d Can anyone provide guidance on how to accomplish this task? ...

show an HTML webpage within a <div> container using AJAX technology

I am trying to include an HTML page named Introduction.html (located in the same folder as x.html) within div1. However, it does not seem to be loading properly. Below is a snippet of the code from x.html x.html <!DOCTYPE html> <h ...

Update data in the datatables using values from an array list

Currently, I have two HTML files where I am loading data using JSON and then applying jQuery datatables to them. Now, I need to refresh the data with new parameters. For example: JSON: [ {"name":"jon","sales":"100","set":"SET1"}, {"name":"charlie","sale ...

Combining CodeIgniter4 with Vue.js and Webpack's devServer to handle CORS issues

Exploring Vue & CodeIgniter 4, starting from https://github.com/flavea/ci4-vue. No matter what I try, I encounter a persistent CORS error in dev mode: Access to XMLHttpRequest at 'http://example.com/public/api/book/get' from origin &apo ...

Utilize the dimensions of one image to resize others using the JavaScript method .getBoundingClientRect

I am attempting to transfer the width and height measurements of the initial image to all subsequent images on the page. Currently, I have successfully applied the dimensions of the first image to the second one, but I am facing difficulties with the thir ...

AutoComplete issues a warning in red when the value assigned to the useState hook it is associated with is altered

const [selectedCountry, setSelectedCountry] = useState(); <Autocomplete autoHighlight={true} //required autoSelect={true} id="geo-select-country" options={availableCountries} value={se ...

Is there a way to alter the CSS padding class for collapsed elements?

I've created a navbar by following Bootstrap's tutorial, but I'm facing an issue with the padding. I used the Bootstrap class "pe-5" to add padding to a form within the navbar so that it aligns to the right with some space from the screen ed ...

Struggling to grasp the concept of nested scope within AngularJs

I found myself puzzled while reading an article on this particular website (pitfall #5): My query is: Does this situation resemble having two variables with the same name in plain JavaScript, where one is locally defined (e.g. within a nested function ...

Issue encountered while attempting to host an ejs file using Express in Node.js

I'm encountering an issue while attempting to serve an .ejs file using express. The error I'm getting is as follows: Error: No default engine was specified and no extension was provided. at new View (C:\development\dashboard& ...

Is there a way to efficiently include numerous jQuery scripts in a batch process, each with a slight variation, using a loop?

Currently, I have a script that calculates the blur effect for multiple images based on the mouse position and scroll position. However, I am looking for a more efficient way to apply this to around 100 images without duplicating the script each time. var ...