Apex: Sorting a Map - salesforce

I have a Map of type Sobject as a key and Integer as a value. The Sobject has field of type Text, other field of type date and another field of type Number(16,2). When I put data into the map and then debug it, the map returns data in a sorted way. The map sorts it by the Number field present in the Key i.e the number data field of the object. Can I get the map sorted by the date field of the object which is its key? Below is the rough structure of my Map and the key object fields.
Map<Effort_Allocation__c, Double> cellContent;
Effort_Allocation__c.Allocated_Effort_Hours__c; //The Number field by which the map gets sorted
Effort_Allocation__c.Assignment_Date__c; // The date field by which I want the map to get sorted

It's a bad idea to use an object as a key for a map. You should, instead, use the object's ID as the key. The reasons for this are discussed in detail here. Short version - the object's values may change which changes the object's hash value and wrecks your map.
Although maps cannot be sorted directly, lists can be sorted, so they can be used to access map elements in sorted order. You'll need a wrapper class for your object that implements the "Comparable" interface. There's an example of that here. Note that the example sorts by date.
The class is declared with "comparable"
global class AccountHistoryWrapper implements Comparable{
and has the following CompareTo method
global Integer compareTo(Object compareTo) {
// Cast argument to AccountHistoryWrapper
AccountHistoryWrapper aHW = (AccountHistoryWrapper)compareTo;
// The return value of 0 indicates that both elements are equal.
Integer returnValue = 0;
if ( aHW.account.CreatedDate > aHW.account.CreatedDate) {
// Set return value to a positive value.
returnValue = 1;
} else if ( aHW.account.CreatedDate < aHW.account.CreatedDate) {
// Set return value to a negative value.
returnValue = -1;
}
return returnValue;
}

Related

How can do array map inside methods in vuejs

How can ı equalize my array ıd and my value ıd and access value.name I didn't do it
This is my code:
activity(val) {
var act = this.items.map(function (val) {
if (element.ActivityID== val) {
return element.ActivityName
}
return act
});
Perhaps this?
activity (val) {
const activity = this.items.find(item => item.ActivityID === val)
return activity && activity.ActivityName
}
This just finds the item with the corresponding ActivityID and then returns its ActivityName.
Your original code contained several possible mistakes:
Two different things called val.
element doesn't appear to be defined.
The return act was inside the map callback. The activity method itself wasn't returning anything.
Not really clear why you were using map to find a single item. map is used to create a new array with the same length as the original array with each item in the new array determined by the equivalent item in the original array. It 'maps' the items of the input array to the items in the output array.

change key's value across multiple objects at once in JS

I have multiple objects that all have the same keys lets say each object has: name and position. The first object will start with position=0. The second object would have position=1. The third object would have position=2 and so on until we get to the 10th object that would have position=9.
I need a way to subtract 1 from every objects position (with only possible values being 0-9 so that 0-1=9)
Looking for a solution that handles all of them mathematically at once, not just re-writing out new values to assign to each key individually.
Suppose you have an array of JavaScript objects, you could use map:
var newObjs = objects.map(function (object) {
object.position = (object.position === 9 ? 0 : object.position--);
return object;
});
A better approach would be:
objects.forEach( function (object) {
object.position--;
object.position = object.position < 0 ? 9 : object.position;
});

Comparing array with array of hashes and outputing new array of hashes

I have an array of subscription instances #subscription_valids and an array of subscribed player that look like that :
array_subscribed_players = [{"name0" => "link1"}, {"name1"=>"link2"}, {"name2"=>"link3"}....]
What I need to do is : for each subscription in #subscription_valids :
#subscription_valids.each do |subscription|
I need to check if subscription.user.full_name or if subscription.user.full_name_inversed matches a key in one of the hashes of array_subscribed_player (in the exemple "name0", "name1" or "name2").
If it matches then I should store the relevant subscription as key in a hash in a new array and extract the relevant link as value of this hash. My final outpout should be an array that looks like this :
[{subscription1 => "link1"}, {subscription2 => "link2}, ...]
else if the subscription.user.full_name doesnt match i'll just store the subscription in a failure array.
How can I achieve this result ?
See http://ruby-doc.org/core-2.2.3/Hash.html
A user-defined class may be used as a hash key if the hash and eql?
methods are overridden to provide meaningful behavior. By default,
separate instances refer to separate hash keys.
so I think you should override your .eql? method in #subscription_valids to something meaningful (like a unique string)
I can't think for a Array method so you can go like:
demo
results = []
failures = []
#subscription_valids.each do |subscription|
array_subscribed_players.each do |player|
if player.keys.first == subscription.user.full_name || player.keys.first == subscription.user.full_name_inversed
results << { subscription => player[player.keys.first] }
else
failures << subscription
end
end
end
You can try the following:
valid = array_subscribed_players.select{|x| #subscription_valids.map(&:name).include?(x.keys.first)}
Demo
If you need to store both valid and invalid values somewhere:
valid, invalid = array_subscribed_players.partition{|x| #subscription_valids.map(&:name).include?(x.keys.first)}

as3 check for 2 objects with same property in array

I have an array, lets call it _persons.
I am populating this array with Value Objects, lets call this object PersonVO
Each PersonVO has a name and a score property.
What I am trying to do is search the array &
//PSEUDO CODE
1 Find any VO's with same name (there should only be at most 2)
2 Do a comparison of the score propertys
3 Keep ONLY the VO with the higher score, and delete remove the other from the _persons array.
I'm having trouble with the code implementation. Any AS3 wizards able to help?
You'd better use a Dictionary for this task, since you have a designated unique property to query. A dictionary approach is viable in case you only have one key property, in your case name, and you need to have only one object to have this property at any given time. An example:
var highscores:Dictionary;
// load it somehow
function addHighscore(name:String,score:Number):Boolean {
// returns true if this score is bigger than what was stored, aka personal best
var prevScore:Number=highscores[name];
if (isNaN(prevScore) || (prevScore<score)) {
// either no score, or less score - write a new value
highscores[name]=score;
return true;
}
// else don't write, the new score is less than what's stored
return false;
}
The dictionary in this example uses passed strings as name property, that is the "primary key" here, thus all records should have unique name part, passed into the function. The score is the value part of stored record. You can store more than one property in the dictionary as value, you'll need to wrap then into an Object in this case.
you want to loop though the array and check if there are any two people with the same name.
I have another solution that may help, if not please do say.
childrenOnStage = this.numChildren;
var aPerson:array = new array;
for (var c:int = 0; c < childrenOnStage; c++)
{
if (getChildAt(c).name == "person1")
{
aPerson:array =(getChildAt(c);
}
}
Then trace the array,

How to keep track of objects in an Array?

I need help in keeping track of objects in an array. I have tried giving each object an arrayIndex var, so I can splice by getting that var which represents the index in the Array.
object0.arrayIndex = 0;
object1.arrayIndex = 1;
object2.arrayIndex = 2;
object3.arrayIndex = 3;
But this is problematic if you move objects to different arrays. Objects would move from different places and therefore the arrayIndex var needs to be constantly updated.
I have done this by adding an static ID to each object. With a for loop I check each object for the corresponding object ID I want to splice
var objectID:Number = objectArrayTarget.id;
for (var t:int; t<_objectArrayLayer1.length; t++)
{
if (objectID == _objectArrayLayer1[i].id)
{
var indexOfObject:Number = (_objectArrayLayer1.indexOf(_objectArrayLayer1[i]));
}
}
_objectArrayLayer1.splice(indexOfObject, 1);
While this works is there a more efficient way of keeping track of objects in an Array? With 100+ objects this might create some slowdown
P.S. These objects are getting spliced and then pushed to a new array.
If your "Objects would move from different places" means same object from one place to another place, there is no arrayIndex needed
var indexOfObject:Number = _objectArrayLayer1.indexOf(targetObj);
if (indexOfObject >= 0) {
_objectArrayLayer1.splice(indexOfObject, 1);
}
If it means different object, like a copy, you could compare some properties to get the targetObj
for (var t:int = 0; t<_objectArrayLayer1.length; t++)
{
if (targetObj.id == _objectArrayLayer1[i].id)//assume id is unique key of the object
{
break;//i is the index here
}
}
if (i != _objectArrayLayer1.length) {//find target object
}
If the object type has a unique key, like a id, or you can make a unique key with some properties of the object, like name + "_" + order, you could use dictionary, Like Patel mentioned.
var dic:Dictionary = new Dictionary(true);
dic[obj1.id] = obj1;
dic[obj2.id] = obj2;//assume id the unique key,or you can use other key
So you can find obj like this
var obj:Object = dic[target.id]
Instead of using an Array.
I think you should use a Set implementation like Hashset
You'll get constant-time lookup, no sorting required,you can add,remove and lookup for object.

Resources