Get an value's key inside a map object [duplicate] - javascript

This question already has answers here:
How can I get a key in a JavaScript 'Map' by its value?
(11 answers)
Closed 14 days ago.
This post was edited and submitted for review 14 days ago and failed to reopen the post:
Original close reason(s) were not resolved
const dict = new Map([
['a', '1'],
['b', '2']
]
We know that dict.get(key) returns the value but what if I want to get the key of value?
This question was never asked. I searched for 3 hours on stack overflow they all create sets or something I don't need

Generally if you have two-way data that you need to access, you either have two maps if a key could be the same as a value, otherwise just a single map.
When you add something to one of these maps, make sure to add it to the other, with the keys/values swapped.
const dict1 = new Map([
['a', '1'],
['b', '2']
]);
// automatically make the second, inverted map
const dict2 = new Map([...dict1.entries()].map(([k, v]) => [v, k]));
console.log(dict2.get('1'));
If you wanted to, you could also make your own class that uses Maps under the hood to make the interface easier to work with.

Related

Variation: Find the object with the highest value in Javascript [duplicate]

This question already has answers here:
Getting key with the highest value from object
(9 answers)
Closed 9 months ago.
In Finding the max value of an attribute in an array of objects there are many (great) answers that report the highest value in an array, but they leave out the option that the object with the highest value would be the desired result to report.
I'm looking for the best way to search for the highest value in an array and return the object that has this value. For example, the expected result of checking this array:
{
"Intent": {
"FileComplaint": 0.000,
"UnsubscribeMe": 0.995,
"TrackRefund": 0.001,
"AskSwitchAccount": 0.00
}
would be: "UnsubscribeMe" or "UnsubscribeMe": 0.995.
Anyone who can help?
Edit:
I found a question that is better formulated than mine and it has great answers:
Getting key with the highest value from object
const obj={Intent:{FileComplaint:0,UndermineGovernment:0.45,UnsubscribeMe:.995,TrackRefund:.001,AskSwitchAccount:0}};
// Get the entries as a nested array of key/value pairs
const entries = Object.entries(obj.Intent);
// Sort the entries by value (index 1),
// and then pop off the last entry destructuring
// the key/value from that array in the process
const [key, value] = entries.sort((a, b) => a[1] > b[1]).pop();
// Log the resulting object
console.log({ [key]: value });

How to make all objects into one array and remove duplicates? [duplicate]

This question already has answers here:
Remove duplicate values from JS array [duplicate]
(54 answers)
Closed 1 year ago.
I have this object, and I want Remove duplicates and make it into one array
var sports = [
['basketball','fotball','racing'],
['fotball','basketball','swimming'],
];
What is the best way to get it like this:
['basketball','fotball','racing','swimming'],
The flat() will make the sports into one array, and is probably the best option here?
Just have to remove the duplicates any tips?
use below:
[...new Set(sports.flat())]
Here sports.flat() flatten out the array. See the doc here
and new Set() will make them unique. See the doc here

How can I remove all duplicated elements in an array (including first occurrence) [duplicate]

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Merge sorted arrays and remove duplicates javascript
(5 answers)
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
I was studying JS in CodeWars and I didn't find a method to remove all duplicated elements in an array. I need to do exactly this:
a = [1,2,2,2,3,4,5,6,6,7]
b = [1,2,7,8,9]
Return a unique array = [3,4,5,8,9]
delete all the duplicated items, including the first occurrence
How can I do this? I already use for, if, forEach, but no success.
You may simply
count the occurences of each element (to preserve the original element types, you may apply Array.prototype.reduce() together with Map against merged array)
then, filter out those that are seen more than once:
const a = [1,2,2,2,3,4,5,6,6,7],
b = [1,2,7,8,9],
uniques = [
...[...a, ...b]
.reduce((acc,item) =>
(acc.set(item, (acc.get(item)||0)+1), acc), new Map)
.entries()
].reduce((acc, [key, value]) =>
(value === 1 && acc.push(key), acc), [])
console.log(uniques)
.as-console-wrapper {min-height:100%}

Remove duplicates in an array of objects in javascript [duplicate]

This question already has answers here:
How to remove all duplicates from an array of objects?
(77 answers)
Closed 2 years ago.
I have an array of objects which is similar to:
Questions-answers [{"questions":"Q_18002_Error_message","answers":"Yes"},{"questions":"Q_18002_Error_message","answers":"No"},{"questions":"Q_18001","answers":"No"}]
I want to delete {"questions":"Q_18002_Error_message","answers":"Yes"} because I have a new updated answer to the question Q_18002,
I am a newbie in Javascript and I am stuck on how to delete the duplicate elements but based on the questions only and delete the old ones and leave the new objects. I hope that I made it clear.
You may build up the Map (with Array.prototype.reduce()) using questions as a key, overwriting previously seen values, then extract array of unique records with Map.prototype.values():
const src = [{"questions":"Q_18002_Error_message","answers":"Yes"},{"questions":"Q_18002_Error_message","answers":"No"},{"questions":"Q_18001","answers":"No"}],
result = [...src
.reduce((r,o) => (r.set(o.questions,o), r), new Map)
.values()
]
console.log(result)
.as-console-wrapper{min-height:100%;}

How to compare an array of submitted quiz answers with an array of correct answers in javascript

I've built a multiple choice quiz. Some of the questions have a single correct answer (using radio input), others have multiple correct answers (checkboxes).
When the user submits the quiz I collect all of the checked radio boxes and checkboxes and push the id of the answer to an array which heads to the server. It looks like this:
userAnswers = [ '1c', '2d', '3a', '3b', '3c', '3d', '4b', '5c', '5d', '6d', '7c', '7d' ]
On the server I have an array of all the correct answers.
correctAnswers = [ '1c', '2d', '3b', '3d', '4b', '5a', '5d', '6d', '7c', '7d' ]
I've tried using underscore's _.difference function to compare the arrays but that doesn't give me a complete comparison.
Can anyone help me devise a way to grade these quizzes? I think the problem is that some of the questions have multiple answers so technically someone could tick all 4 checkboxes or just one, it makes it harder to compare them.
Maybe using arrays isn't the best way to do this, any suggestions are appreciated!
Maybe using arrays isn't the best way to do this
Yes, you really should use an appropriate data structure for this:
answers = [
['c'], // 1
['d'], // 2
['a', 'b', 'c', 'd'], // 3
['b'], // 4
['c', 'd'], // 5
['d'], // 6
['c', 'd'] // 7
]
You could also use an object for "named" questions (instead of indexing them), and possibly drop the array wrapper for single-choice questions, but I'd argue for arrays because of their simplicity here.
If you want to use your original format as input (e.g. because it's easier to type or your server doesn't support nesting URL query parameters), you can easily convert it to the nested arrays.
Comparing the results with the correct answers question-for-question should be trivial then.

Categories