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 });
Related
This question already has answers here:
Javascript sort array of objects using array of priority
(2 answers)
Closed 1 year ago.
var array = [{value:"13",type:"Fruit"},{value:"61",type:"Animal"},
{value:"19",type:"Fruit"},{value:"71",type:"Animal"},
{value:"12",type:"Fruit"},{value:"15",type:"Fruit"},
{value:"11",type:"Plant"},{value:"10",type:"Fruit"},
{value:"16",type:"Plant"}]
What is the best/optimized way to sort this array such that I get all elements of type Fruit first and then the elements of type Animal (by picking elements from end of array).
expectedOutput = [{value:"10",type:"Fruit"},
{value:"15",type:"Fruit"},{value:"12",type:"Fruits"},
{value:"19",type:"Fruit"},{value:"13",type:"Fruit"},
{value:"71",type:"Animal"},{value:"61",type:"Animal"},
{value:"16",type:"Plant"},{value:"11",type:"Plant"}]
Note:- I don't need to sort it Alphabetically. It must be sort depending upon the specific type.
You can store the order of the type properties in an array, then subtract the index of the type property when sorting to determine precedence:
const order = ["Fruits", "Animal"]
var array = [{value:"13",type:"Fruit"},{value:"61",type:"Animal"},
{value:"19",type:"Fruit"},{value:"71",type:"Animal"},
{value:"12",type:"Fruit"},{value:"15",type:"Fruit"}]
const sorted = array.sort((a,b) => order.indexOf(a.type) - order.indexOf(b.type))
console.log(sorted)
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%}
This question already has answers here:
remove all elements that occur more than once from array [duplicate]
(5 answers)
How to remove all duplicates from an array of objects?
(77 answers)
Completely removing duplicate items from an array
(11 answers)
Closed 1 year ago.
I have an array of objects with input like below
var jsonArray1 = [{id:'1',name:'John'},{id:'2',name:'Smith'},{id:'3',name:'Adam'},{id:'1',name:'John'}]
The id 1 appears twice and I would like to drop all duplicate records .i.e. my output should look like
[{id:'2',name:'Smith'},{id:'3',name:'Adam'}]
Can you please guide/direct me in how I can drop all duplicate records
Create Map from an array where key of the Map is your desired id, duplicated won't be preserved (only last occurrence will). After just take the values from Map.
Removing all of occurrences of duplicates (this is what OP wanted):
const input = [{id:'1',name:'John'},
{id:'2',name:'Smith'},
{id:'3',name:'Adam'},
{id:'1',name:'John'}]
const res = input.filter((x, i, arr) =>
arr.filter(e => e.id === x.id).length === 1)
console.log(res)
Preserving 1 occurrence of duplicates:
const input = [{id:'1',name:'John'},
{id:'2',name:'Smith'},
{id:'3',name:'Adam'},
{id:'1',name:'John'}]
const unique = [...new Map(input.map(item => [item.id, item])).values()]
console.log(unique)
This question already has answers here:
How to sort an array of integers correctly
(32 answers)
Closed 2 years ago.
I am trying to sort a map using below function
var m=new Map();
m.set('0900','0910');
m.set('1100','1200');
m.set('1000','1030');
m.set('1235','1240');
var ma=new Map([...m.entries()].sort());
console.log(ma);
Output:{ 900 => 910, 1000 => 1030, 1100 => 1200, 1235 => 1240}
the map is getting sorted, but when I use the integers instead of characters I can't able to sort it
var m=new Map();
m.set(0900,0910);
m.set(1100,1200);
m.set(1000,1030);
m.set(1235,1240);
var ma=new Map([...m.entries()].sort());
console.log(ma)
Output:
{1000 => 1030, 1100 => 1200, 1235 => 1240, 900 => 910}
sort() function, when you don't supply a compareFunction as an argument, does not really work the way you instinctively expect it to work. See the following quote from relevant MDN page:
If compareFunction is not supplied, all non-undefined array elements
are sorted by converting them to strings and comparing strings in
UTF-16 code units order. For example, "banana" comes before "cherry".
In a numeric sort, 9 comes before 80, but because numbers are
converted to strings, "80" comes before "9" in the Unicode order. All
undefined elements are sorted to the end of the array.
The numeric sort bit in the quote explains why you're getting two different sorts with strings and numbers (with "0900" and 900). To overcome this, simply provide a function to the sort to the comparisons the way you want it, like so:
let ma = new Map([...m.entries()].sort((a, z) => a[0] - z[0]);
You can look into the details of how these compareFunctions work in the same MDN page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Here, extract the first element with the help of destructuring out of the array and compare it.
var m=new Map();
m.set(0900,0910);
m.set(1100,1200);
m.set(1000,1030);
m.set(1235,1240);
var ma=new Map([...m.entries()].sort(([a], [b]) => a - b));
for(const e of ma) {
console.log(e);
}
MDN on Map.entries():
The entries() method returns a new Iterator object that contains the [key, value] pairs for each element in the Map object in insertion order.
When calling .sort() on the entries, it first converts the key-value pairs into strings before sorting them. That means that 0900 becomes 900, which comes after 1235, because '9' > '1' (first character of each string).
If you want to sort the entries by key, you will need to pass in a custom compareFunction argument to sort, which handles the key-value pairs and compares the keys as numbers:
var m = new Map();
m.set(0900,0910);
m.set(1100,1200);
m.set(1000,1030);
m.set(1235,1240);
var ma = new Map([...m.entries()].sort((kv1, kv2) => kv1[0] - kv2[0]));
console.log(ma);
This question already has answers here:
How to get a key in a JavaScript object by its value?
(31 answers)
Closed 4 years ago.
I have a key value pair array in js
var tabList = {0:'#description', 1:'#media', 2:'#attributes', 3:'#calendar', 4:'#pricing'}
I'm using the keys to get the values in my code
ie. tabList[2] returns #attributes
I thought I could do the same in reverse to get the key
tabList[#media] and have it return 1
But this doesn't work
How can I fetch the key with only the value as input?
There are plenty of solutions here Swap key with value JSON
I will flip key with values 1st
var tabList = {0:'#description', 1:'#media', 2:'#attributes', 3:'#calendar', 4:'#pricing'}
let flipped=Object.assign({}, ...Object.entries(tabList).map(([k,v]) => ({ [v]: k })))
console.log(flipped);
console.log(flipped['#description']);