我有一段 JavaScript 代码,可以根据数组生成模式。
下面的数组:
[1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5, 4, 3, 2, 1]
将返回:
[1, 1, 1, 1, -1, -1, -1, -1, 1, 1, 1, 1, -1, -1, -1, -1]
但是,我希望简化模式并只获得唯一的序列:
[1, 1, 1, 1, -1, -1, -1, -1]
有什么方法可以使用 slice()
或 filter()
实现此目的吗?
如果没有,那么我该怎么做有什么建议吗?
请注意,数组模式和唯一序列的长度是可变的。
最佳答案
抱歉,关于另一个答案。我很快。
// Ask the original sequence as parameter
function uniqueSequence(originalSequence){
return
originalSequence
.map(function(value, index){ // Get difference between each number.
return value - originalSequence[index - 1]; // Somthing like [1,2,3,2,1] => [NaN, 1,1,-1,-1]
})
.toString() // Parse that result to string format => "NaN,1,1,-1,-1"
.match(/N((,[0-9-]+)*?)\1*$/)[1] // we look for the shortest pattern of comma-separated integers
// (,\d+) starting right after "NaN" and repeating till
// the end of the string. Result in something like => ",1,1,-1,-1"
.substring(1) // Remove the first comma => "1,1,-1,-1"
.split(',') // Convert to array ["1","1","-1","-1"]
.map(function(value){
return parseInt(value); // Parse each element to integer [1,1,-1,-1]
});
}
用最短的代码(ES6)
f=_=>_.map((a,i)=>a-_[i-1]).toString().match(/N((,[0-9-]+)*?)\1*$/)[1].substring(1).split`,`.map(a=>~~a)
f=_=>_.map((a,i)=>a-_[i-1]).toString().match(/N((,[0-9-]+)*?)\1*$/)[1].substring(1).split`,`.map(a=>~~a)
// Ask the original sequence as parameter
function uniqueSequence(originalSequence){
return originalSequence
.map(function(value, index){ // Get difference between each number.
return value - originalSequence[index - 1]; // Somthing like [1,2,3,2,1] => [NaN, 1,1,-1,-1]
})
.toString() // Parse that result to string format => "NaN,1,1,-1,-1"
.match(/N((,[0-9-]+)*?)\1*$/)[1] // we look for the shortest pattern of comma-separated integers
// (,\d+) starting right after "NaN" and repeating till
// the end of the string. Result in something like => ",1,1,-1,-1"
.substring(1) // Remove the first comma => "1,1,-1,-1"
.split(',') // Convert to array ["1","1","-1","-1"]
.map(function(value){
return parseInt(value); // Parse each element to integer [1,1,-1,-1]
});
}
console.log(f([1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5, 4, 3, 2, 1]))
console.log(uniqueSequence([1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5, 4, 3, 2, 1]))
关于javascript - 获取数组中唯一序列的最短方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50838691/