区分数组中的范围,并展开它们

时间:2017-10-06 07:47:53

标签: javascript arrays string loops range

我需要区分数组中的范围,然后展开它。我正在使用JavaScript。

例如:

var output =["1", "6", "4", "5", "9", "10", "11", "13", "14", "15"];

所需的输出是

var range = "1-6";
range = str.split("-");

start = parseInt(range[0]);
end = parseInt(range[1]);

var rangeArray = [];

for(var i = start; i <= end; i++){
    rangeArray.push(i);
}
console.log(rangeArray); 

我目前有脚本扩展某个范围。我很难确定数组中的范围:

git add .    
git commit -m "make changes"    
git push heroku master

8 个答案:

答案 0 :(得分:1)

尝试这种方法。循环遍历数组并检查项目是否包含-符号,如果是,则将其拆分并获取范围。循环遍历范围并将每个项目添加到数组中。否则只需添加该项目。对于这个逻辑,您还可以创建一个辅助函数,该函数返回给定范围内的数组,并concat使用原始数组范围。

&#13;
&#13;
const arr = ["1", "6", "4", "5", "9-11", "13-15"];
let newArray = [];

function getRange(start, count) {
   const arr = [];
   for(let i = start; i <= count; i++) {
       arr.push(i.toString());
   }  
   return arr;
}

arr.forEach(item => {
  if(item.includes('-')) {    
    const [start, end] = item.split('-').map(n => parseInt(n));
    newArray = newArray.concat(getRange(start,end));
  } else {
    newArray.push(item);
  }
});

console.log(newArray);
&#13;
&#13;
&#13;

您也可以使用reduce方法

执行此操作

&#13;
&#13;
const arr = ["1", "6", "4", "5", "9-11", "13-15"];

function getRange(start, count) {
   const arr = [];
   for(let i = start; i <= count; i++) {
       arr.push(i.toString());
   }   
   return arr;
}

const newArray = arr.reduce( (arr, item) => {
  if(item.includes('-')) {  
    const [start, end] = item.split('-').map(n => parseInt(n));
    arr = arr.concat(getRange(start, end));
  } else {
    arr.push(item);
  }  
  return arr;
}, []);

console.log(newArray);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

我更新了你的代码,使splitRanges函数返回一个范围内的所有数字,并在初始数组上循环,并使用此函数提取每次迭代中的所有范围:

var arr = ["1", "6", "4", "5", "9-11", "13-15"]

function splitRanges(rangeStr) {
  var range = rangeStr.split("-");
  var start = parseInt(range[0]);
  var end = parseInt(range[1]);
  var rangeArray = [];

  for (var i = start; i <= end; i++) {
    rangeArray.push(""+i+"");
  }
  return rangeArray;
}

var output = [];

arr.forEach(function(r){
    if(r.indexOf("-")>-1){
      output = output.concat(splitRanges(r));
    }else
      output.push(r);
});
console.log(output);

<强>解释

此代码循环遍历初始数组,并在每次迭代中检查它是否为范围将此值传递给splitRanges函数并将concat结果传递给输出数组,否则仅push output数组中的值。

答案 2 :(得分:1)

你可以这样做:

let arr = ["1", "6", "4", "5", "9-11", "13-15"];
let out = [];
const range = (start, end) => Array.from({length: (end - start)}, (v, k) => k + start);
arr.forEach(item => {
   let splitted = item.split('-');
    if(splitted.length > 1) {
        out.push(...range(parseInt(splitted[0]), parseInt(splitted[1]) + 1));
    } else {
        out.push(parseInt(item))
    }
})
console.log('out: ', out); // [1, 6, 4, 5, 9, 10, 11, 13, 14, 15]

答案 3 :(得分:0)

看起来您可以区分范围,如果它包含“ - ”,不是吗?

arr.forEach((val) => {
    if (val.indexOf("-") > -1) {
        // do something here
    }
})

对于// do something here,您将获取已有的内容并将其转换为函数:

function getArrayFromRange(range) {
    range = str.split("-");

    start = parseInt(range[0]);
    end = parseInt(range[1]);

    var rangeArray = [];

    for(var i = start; i <= end; i++){
        rangeArray.push(i);
    }

    return rangeArray;
}

您可以使用您的范围调用该函数,然后将返回值中的值插入arr

中的相应位置

答案 4 :(得分:0)

当你有一个范围时,你可以简单地迭代数组并使用这段代码:

var arr = ["1", "6", "4", "5", "9-11", "13-15"];
var output =[];

for(var j=0;j<arr.length;j++) {

  if(arr[j].search("-")!=-1) {
    range = arr[j].split("-");

    start = parseInt(range[0]);
    end = parseInt(range[1]);

    for(var i = start; i <= end; i++){
        output.push(i);
    } 
  } else {
    output.push(parseInt(arr[j]));
  }

}
console.log(output); 

答案 5 :(得分:0)

// the predefined array
var arr = ["1", "6", "4", "5", "9-11", "13-15"];

// new array will be this
var output = [];

// loop over each item in array
for(i in arr){
  // if array has a '-' character in it
  if(arr[i].indexOf('-') > 0){
     // split the array into start and end range
     var split = arr[i].split('-');
     // loop through start and end
     for(var p = parseInt(split[0]); p < parseInt(split[1]) + 1; p++){
         // push it to the new array
         output.push(p.toString());
     }
  }else{
    // the item doesn't contain '-', push it directly
    output.push(arr[i].toString());
  }
}
console.log(output);

答案 6 :(得分:0)

对我而言,看起来你是在追求这样的事情,但也许我错了:

var arr = ["1", "6", "4", "9-11", "13-15"];

var output =[
    [0, 1],
    [0, 1, 2, 3, 4, 5, 6],
    [0, 1, 2, 3, 4],
    [9, 10, 11],
    [13, 14, 15]
];

var ranges = arr.map(function(item) {
    var range = item.split('-');
    if (range.length === 2) {
        var start = parseInt(range[0]);
        var end = parseInt(range[1]);
    } else {
        start = 0;
        end = parseInt(range[0]);
    }
    
    var rangeArray = [];

    for(var i = start; i <= end; i++){
        rangeArray.push(i);
    }
    
    return rangeArray;
});

答案 7 :(得分:0)

您可以使用while循环返回范围的单个值。

var array = ["1", "6", "4", "5", "9-11", "13-15"],
    result = array.reduce(function (r, a) {
        var p = a .split('-');
        do {
            r.push((p[0]++).toString());
        } while (p[0] <= p[1])
        return r;
    }, []);
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }