问题描述
我正在遵循以下逻辑,但我仍然缺少一些东西。
给出一个像const testArr = ["F","F","C","F"]
这样的数组。
结果数组应类似于["F",["C","C"],["C"],"F"]
。
到目前为止我提出的代码如下:
const grouping = (arr) => {
const result = [];
arr.forEach((item,index) => {
if (item === "C") {
const subArr = new Array();
subArr.push(item);
if (arr[index + 1] !== "C") {
result.push(subArr);
}
} else {
result.push(item);
}
});
return result;
};
console.log(grouping(testArr));
这将当前打印结果:
["F","F"]
感谢您的提示:-)
解决方法
您可以使用带有临时索引的while循环来达到预期的结果
以下是从您当前的解决方案中修改的小部分(更改为for
循环,并使用while
进行条件检查)
const testArr = ["F","F","C","F"]
const grouping = (arr) => {
const result = []
for (let index = 0; index < arr.length; index++) {
if (arr[index] === "C") {
const subArr = [arr[index]]
let tempIndex = index + 1
while (arr[tempIndex] === "C") {
subArr.push(arr[tempIndex])
index = tempIndex
tempIndex++
}
result.push(subArr)
} else {
result.push(arr[index])
}
}
return result
}
console.log(grouping(testArr))
,
我想我会这样做,请参见评论:
const grouping = arr => {
const result = [];
let currentSub = null;
for (const value of arr) {
// Is it the special value?
if (value === "C") {
// Yes,do we have an active array?
if (!currentSub) {
// No,create one and push it
currentSub = [];
result.push(currentSub);
}
// Add to the active array
currentSub.push(value)
} else {
// Not special,forget active array and push
currentSub = null;
result.push(value);
}
}
return result;
};
实时示例:
const testArr = ["F","F"]
const grouping = arr => {
const result = [];
let currentSub = null;
for (const value of arr) {
// Is it the special value?
if (value === "C") {
// Yes,forget active array and push
currentSub = null;
result.push(value);
}
}
return result;
};
console.log(grouping(testArr));
.as-console-wrapper {
max-height: 100% !important;
}
如果您更喜欢forEach
而不是for-of
,则几乎是相同的:
const testArr = ["F","F"]
const grouping = arr => {
const result = [];
let currentSub = null;
arr.forEach(value => {
// Is it the special value?
if (value === "C") {
// Yes,forget active array and push
currentSub = null;
result.push(value);
}
});
return result;
};
console.log(grouping(testArr));
.as-console-wrapper {
max-height: 100% !important;
}
旁注:通常,避免使用new Array()
。要创建一个空白数组,只需使用[]
。要使用条目创建数组,请使用[value1,value2]
等。您可以使用new Array(x)
(或仅使用Array(x)
)创建长度为{{1的 sparse 数组}},但这通常仅在要在其上使用x
以便在每个条目中为其填充相同值时有用。
我将使用一个临时数组来存储“特殊”值,并且在遇到其他值时会重置它。
const grouping = (arr) => {
const result = []
let tempC = []
arr.forEach(letter => {
if (letter === 'C') {
tempC.push('C') // Append the special letter to its temp array
} else {
if (tempC.length > 0) {
result.push(tempC) // If the previus iteration had a 'C',push the array in result
}
tempC = [] // Reset the tempC collector
result.push(letter) // Add the 'not special' letter to the result
}
})
return result
}
,
const testArr = ["F","F"];
const result = testArr.reduce((acc,val) => {
if (val === "C") {
Array.isArray(acc[acc.length - 1]) ? acc[acc.length - 1].push(val) : acc.push([val]);
} else {
acc.push(val);
}
return acc;
},[]);
console.log(result);
,
这是使用函数Array.prototype.reduce
(DRY)的一种方法。
const testArr = ["F","F"];
const {result} = testArr.reduce((a,e) => {
if (e === a.target) (a.current || (a.current = [])).push(e);
else {
if (a.current) a.result.push(a.current),a.current = undefined;
a.result.push(e);
}
return a;
},{result: [],current: undefined,target: "C"});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
,
void groupElements(int arr[],int n)
{
// Initialize all elements as not visited
bool *visited = new bool[n];
for (int i=0; i<n; i++)
visited[i] = false;
// Traverse all elements
for (int i=0; i<n; i++)
{
// Check if this is first occurrence
if (!visited[i])
{
// If yes,print it and all subsequent occurrences
cout << arr[i] << " ";
for (int j=i+1; j<n; j++)
{
if (arr[i] == arr[j])
{
cout << arr[i] << " ";
visited[j] = true;
}
}
}
}
delete [] visited;
}