2017-05-03 46 views
-3

我有对象的数组:编号对象

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; 
    }; 
}); 

但它不能令人信服。任何正确的方向指导将不胜感激。

+1

你说的小数两侧意味着排序?你的意思是*数字*? – Li357

+0

@Jordão - 我的错误,我纠正了答案 - 并且为了可读性而截断了对象。 –

+0

@AndrewLi - 这不是这么多的情况下或排序,而是根据他们的阵列 –

回答

2

您可以保存组内最后一个值,新组值和偏移量。

var array = [1.1, 1.5, 4, 3.1, 3.3], 
 
    result = array.map(((last, group, offset) => a => { 
 
     offset += 0.1; 
 
     if (Math.floor(last) !== Math.floor(a)) { 
 
      group++; 
 
      offset = a === Math.floor(a) ? 0 : 0.1; 
 
     } 
 
     last = a; 
 
     return group + offset; 
 
    })(0, 0, 0)); 
 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

+1

减少主人再次罢工 - 谢谢这正是我正在寻找 –

+0

减少是美丽的,你可以表达几乎任何可以想象的变化。 –