gpt4 book ai didi

javascript - array.split ("stop here") array to array of arrays in javascript 数组

转载 作者:行者123 更新时间:2023-12-01 16:09:47 28 4
gpt4 key购买 nike

所以我们的目标是在遇到某个元素时将数组分割成子数组下面的示例 array.split("stop here")

["haii", "keep", "these in the same array but", "stop here", "then continue", "until you reach", "another", "stop here", "and finally", "stop here", "stop here"]

[
["haii", "keep", "these in the same array but"], ["then continue", "until you reach", "another"], ["and finally"]
]

到目前为止,我尝试的效果不是很好:

Array.prototype.split = function (element) {
const arrays = [];
// const length = this.length;
let arrayWorkingOn = this;
for(let i=0; i<arrayWorkingOn.length; i++) {
if(this[i] === element) {
const left = arrayWorkingOn.slice(0, i);
const right = arrayWorkingOn.slice(i, arrayWorkingOn.length);
arrayWorkingOn = right;
arrays.push(left);
console.log(right);
}
}
arrays.push(arrayWorkingOn); //which is the last 'right'
return arrays;
}

提前感谢您的时间和努力!

最佳答案

首先 .join() 你的数组在我的例子中有一个唯一的分隔符 UNIQUE_SEPERATOR

然后您首先使用 .split("stop here") 将其拆分,返回一个包含 3 个字符串的数组。

现在您需要 .map() 遍历数组并使用分隔符 (UNIQUE_SEPERATOR) 将其拆分,然后 .filter() 输出 "" 值。

最后,您通过检查其长度来过滤掉空数组,然后就完成了。

let arr = [
"haii",
"keep",
"these in the same array but",
"stop here",
"then continue",
"until you reach",
"another",
"stop here",
"and finally",
"stop here",
"stop here"
];

Array.prototype.split = function() {
return this.join("UNIQUE_SEPERATOR")
.split("stop here")
.map(el => el.split("UNIQUE_SEPERATOR").filter(Boolean))
.filter(arr => arr.length);
};

console.log(arr.split());

关于javascript - array.split ("stop here") array to array of arrays in javascript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63412458/

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