我有对象的数组:编号对象
let _arr =[{obj_num: 1.1}, {obj_num: 1.5}, {obj_num: 4}, {obj_num: 3.1}, {obj_num: 3.3}];
我需要根据小数两侧订购它们的数量,即:
let _arr =[{obj_num: 1.1}, {obj_num: 1.2}, {obj_num: 2}, {obj_num: 3.1}, {obj_num: 3.2}];
对象分组由小数第一个数字组成:So 1.1 & 1.2属于对象组1.
obj_num
中没有小数点的对象在它们自己的组中。
目的需要根据它们的组acsending顺序来编号。
所以,如果obj_num:1.1,obj_num:1.3属于1组,他们应该成为1.1和1.2。
如果obj数1.1,1.3,如图2所示,分别为4.3,以便,他们将需要成为1.1,1.2,2,3.1。
我难倒,认为我正在做小题大做的。
什么我想现在:
this.data.questions =[{question_num: 1.1}, {question_num: 1.5}, {question_num: 4}, {question_num: 3.1}, {question_num: 3.3}];
let _normalQuestionRef = 0;
let _questionRef = {
totalObjs: _arr.length,
objects: {},
};
// Create a reference object that groups questions by the number before the decimal
this.data.questions.forEach((_q, _i) => {
let _qNum = _q.question_num.split('.')[0];
_questionRef.questions[`question_${_qNum}`] = _questionRef.questions[`question_${_qNum}`] || [];
_questionRef.questions[`question_${_qNum}`].push({
index: _i,
q: _q,
});
});
// Re-populate the original array
Object.keys(_questionRef.questions).forEach((_qRef) => {
let _qSet = _questionRef.questions[_qRef];
// Increment the base question number
_normalQuestionRef ++;
// If there are questions with a decimal point number
if (_qSet.length > 1) {
// Loop each decimal point and place it in the specified index of the array
_qSet.forEach((_q, i) => {
_q.q.question_num = _normalQuestionRef + '.' + String(i + 1);
this.data.questions[_q.index] = _q;
});
} else {
// Just add it as is
_qSet[0].q.question_num = _normalQuestionRef;
this.data.questions[_qSet[0].index] = _qSet[0].q;
};
});
但它不能令人信服。任何正确的方向指导将不胜感激。
你说的小数两侧意味着排序?你的意思是*数字*? – Li357
@Jordão - 我的错误,我纠正了答案 - 并且为了可读性而截断了对象。 –
@AndrewLi - 这不是这么多的情况下或排序,而是根据他们的阵列 –