数组中特定元素的组合

时间:2019-06-05 12:24:04

标签: javascript reactjs

假设我正在做这是因为我的作业。我想为下一周制定某种时间表(6-7个元素的数组-输出结果)。但是我有一个问题。我需要弄清楚如何在数组中放置一个元素,并且他的频率必须恰好是用户输入的内容。元素必须位于数组中的其他索引处。

我收到了用户的这种输入(仅作为示例);

var arrayOfElements = ["el1","el2","el3"];
var el1Frequency = 3;
var el2Frequency = 2;
var el3Frequency = 1;
//output array of schedule (this is just an example)
var finaloutPutArray = ["el1","el2","el3","el1","el2","el1"];

元素el1的索引基本上是0、3和5,我不希望这样重复元素。

["el1","el1","el2","el3"...];
["el2","el1","el1","el3"];

能否请您给我一些有关如何解决此问题的想法。

我是这样开始的

var finalSchedule = [];

var totalDaysPerWeek = 6;
for(var i =0; i < totalDaysPerWeek; i++) {
  ...
}

1 个答案:

答案 0 :(得分:1)

这是一种模式,请检查我的工作片段:

var arrayOfElements = ["el1","el2","el3"];
var obj = { el1: 3,
            el2: 2,
            el3: 1};
                        
 // First determine the max recurring of an element, this will be the number of cycles fo your loop

// Check key values
var arr =  Object.keys(obj).map(function ( key ) { return obj[key]; });

// Get max value
var max = Math.max.apply( null, arr );
var finalArray = [];

// Iterate from 0 to max val
for(i = 0; i < max; i += 1){
  // Iterate on array of elements
  for(k = 0; k < arrayOfElements.length; k += 1) {
    // If config of recurring
    if( obj[arrayOfElements[k]] >= i+1 ) {
       // Push into array
       finalArray.push(arrayOfElements[k]);
    }
  }
}

console.log(finalArray);