[英]Most concise way to split an array?
String
具有內置方法.split()
但Array
沒有。 為什么?
我能做的最好的是:
Array.prototype.split = function(separator) {
return this.toString().split(separator)
.map(egg => egg.split(',')
.filter(Boolean))
.filter(egg => egg.length);
}
['(', 'name:', 'John', 'Deer', ')', '(', 'name:', 'Jane', 'Doe', ')']
.split(/\(|\)/);
// [['name:', 'John', 'Deer'], ['name:', 'Jane', 'Doe']]
對於一般情況,是否有更簡潔的方法來編寫或更有效的方法?
這看起來如何:
(['(', 'name:', 'John', 'Deer', ')', '(', 'name:', 'Jane', 'Doe', ')'])
.join(',')
.replace(/^\(\,|\,\)$/g, '')
.split(',),(,')
.map(str => str.split(','))
或者
(['(', 'name:', 'John', 'Deer', ')', '(', 'name:', 'Jane', 'Doe', ')'])
.join(',')
.match(/\,?\(\,?(.*?)\,\)\,?/g)
.map( str => str.replace(/\,?[\(\)]\,?/g, '').split(',') );
更新 1(縮短)
function GroupAt( separator, array ){
return (array)
.join(',')
.replace( separator, ',')
.replace( /^\,{1,}|\,{1,}$/g, '')
.split( /\,{2,}/ )
.map(str => str.split(','))
};
const sample = ['(', 'name:', 'John', 'Deer', ')', '(', 'name:', 'Jane', 'Doe', ')'];
console.log(GroupAt(/[\(\)]/g, sample))
console.log(GroupAt( /(\(|\)|John)/g, sample ))
更新:(**見評論)
function GroupAt( separator, array ){
const regString = (separator).toString().replace(/^\/|\/g?i?$/g, '').replace(/\\/, "\\");
return (array)
.join(',')
.replace( new RegExp( "^"+regString+"\\,|\\,"+regString+"$", 'g' ), '')
.replace( new RegExp( '(,?'+ regString +',?){1,}', 'g' ), regString)
.split(regString)
.map(str => str.split(','))
}
const sample = ['(', 'name:', 'John', 'Deer', ')', '(', 'name:', 'Jane', 'Doe', ')'];
console.log(GroupAt(/[\(\)]/g, sample))
console.log(GroupAt( /(\(|\)|John)/g, sample ))
您確定您沒有嘗試構建標記器嗎?
這是一個天真的:
const tokens = ['(', 'name:', 'John', 'Deer', ')',
'(', 'name:', 'Jane', 'Doe', ')'];
const result = tokens.reduce((acc, tk) => {
if (tk === '(') {
acc.current = [];
acc.final.push(acc.current);
}
else if (tk === ')')
acc.current = acc.final;
else
acc.current.push(tk);
return acc;
}, {current: null, final: []}).final;
console.log(result);
結果值為:
[ [ 'name:', 'John', 'Deer' ], [ 'name:', 'Jane', 'Doe' ] ]
這是我為您搜索的內容: https://www.freecodecamp.org/news/how-to-build-a-math-expression-tokenizer-using-javascript-3638d4e5fbe9/
另外,引用 Jamie Zawinski 的話:
有些人在遇到問題時會想“我知道,我會使用正則表達式”。 現在他們有兩個問題。
轉換為字符串是有問題的。 元素應作為不與其他元素結合使用的元素進行測試。 考慮數組:
[ 'hello, world', '3 / 4', '/', 0.7, '1,2,3' ]
這是一個不使用字符串轉換的解決方案,除非比較單個元素。 還支持正則表達式。
Array.prototype.split = function(sep) {
return this.reduce((acc, v, i) => {
if (v == sep || (sep.exec && sep.exec(v))) acc.push([]);
else {
if (i == 0) acc.push([]);
acc[acc.length-1].push(v);
}
return acc;
}, []);
}
測試:
console.log([ 'hello, world', '3 / 4', '/', 0.7, '1,2,3' ].split('/'));
console.log([ 'hello, world', '3 / 4', '/', 0.7, '1,2,3' ].split(0.7));
console.log([ 'hello, world', '3 / 4', '/', 0.7, '1,2,3' ].split(/^hello/));
console.log([ 'hello, world', '3 / 4', '/', 0.7, '1,2,3' ].split(/^hello$/));
console.log([ ].split(1));
結果:
[ [ 'hello, world', '3 / 4' ], [ 0.7, '1,2,3' ] ]
[ [ 'hello, world', '3 / 4', '/' ], [ '1,2,3' ] ]
[ [ '3 / 4', '/', 0.7, '1,2,3' ] ]
[ [ 'hello, world', '3 / 4', '/', 0.7, '1,2,3' ] ]
[]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.