gpt4 book ai didi

javascript - 如何将 "summarize"整数数组转换为具有范围的字符串?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:31:49 24 4
gpt4 key购买 nike

假设您输入了 Array=[1,2,3,5,7,9,10,11,12,15]

输出应该是1-3,5,7,9-12,15

我正在寻找有关我的尝试和其他可能解决方案的反馈。这是我在 javascript 中的尝试:

var min = 0;
var max = -1;

function summarize(array) {
var sumString = "";
var prevVal = -1;

array.forEach(function(currVal, index) {
if (index > 0) {
prevVal = array[index - 1];
}
if (index === 0) {
min = currVal;
max = currVal;
} else if (currVal - prevVal === 1) {
max = currVal;
} else if (min !== max && max !== -1) {
sumString += min + "-" + max + (index < array.length - 1 ? "," : "");
min = currVal;
max = -1;
} else {
sumString += min + (index < array.length - 1 ? "," : "");
}

if (index === array.length - 1) {
if (max === -1) {
sumString += "," + min;
} else {
sumString += min + "-" + max;
}
}
});
return sumString;
}

最佳答案

下面是一个稍微简短的实现:

var i = 0, prev, arr = [1,2,3,5,7,9,10,11,12,15], out = [];
for(i=0; i<arr.length; prev = arr[i], i++) {

// if the current number is not prev+1, append it to out
// Note that we are adding it as a string, to ensure that
// subsequent calls to `split()` (see else part) works
if(prev !== arr[i] - 1) out.push(String(arr[i]));

// if the current number is prev+1, modify the last value
// in out to reflect it in the RHS of - (hyphen)
else out[out.length - 1] = [out[out.length - 1].split('-')[0], String(arr[i])].join('-');
}

// out => ["1-3", "5", "7", "9-12", "15"]

关于javascript - 如何将 "summarize"整数数组转换为具有范围的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32610428/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com