Scenario
when we try to sort item , category, Size option etc based on internalID then because of the disarray we are not able to sort in sequence.
so we need to add new object to the array and we need to sort the array based on that newly added object.
Solution
Create a Extension with proper name
Extend the required view (In the below example we have extended ProductViewsOption.View)
use the below code ( Here in this Example we are sorting the Size Option)
mountToApp: function mountToApp(container) {
_.extend(ProductViewsOptionView.prototype, {
getContext: _.wrap(ProductViewsOptionView.prototype.getContext,function (fn) {
var originalRet = fn.apply(this, _.toArray(arguments).slice(1));
var optionarray = originalRet.values;
console.log(‘optionarray’,optionarray);
// Define a mapping object for “label” values to corresponding new field values
const labelToNewFieldValueMapping = {
XS: 0,
SM: 1,
MD: 2,
LG: 3,
LGT: 4,
XL: 5,
XLT: 6,
‘2X’: 7,
‘2XT’: 8,
‘3X’:9,
‘3XT’:10,
‘4X’:11,
‘4XT’:12,
‘5X’:13,
‘5XT’:14,
‘6X’:15,
‘6XT’:16,
‘7X’:17,
‘7XT’:18,
};
// Function to add a new field with different values based on the “label” value
function addNewFieldToObject(obj) {
const newValue = labelToNewFieldValueMapping[obj.label] || ‘ ‘;
return {
…obj,
tosort: newValue,
};
}
// Use map() to add the new field with different values based on the “label” value to each object
const updatedArrayOfObjects = optionarray.map(addNewFieldToObject);
console.log(“updatedArray”,updatedArrayOfObjects);
function compareByNewField(a, b) {
if (a.tosort < b.tosort) return -1;
if (a.tosort > b.tosort) return 1;
return 0;
}
// Sort the array based on the “newField” value
const sortedArrayOfObjects = updatedArrayOfObjects.sort(compareByNewField);
// console.log(‘sortedArrayOfObjects’,sortedArrayOfObjects);
originalRet.values = sortedArrayOfObjects;
return originalRet;
}
),
});
},