javascript - 在每次出现特定子字符串时剪切数组中存在的 JS 字符串并附加到同一数组

标签 javascript arrays string substring indexof

注意: 此时此刻,我无法更好地表达问题标题。如果有人能够更好地理解它,请继续!

我有什么:

var array = ["authentication.$.order", "difference.$.user.$.otherinformation", ... , ...] 

我需要什么:

["authentication", "authentication.$", "authentication.$.order",
"difference", "difference.$", "difference.$.user", "difference.$.user.$", 
"difference.$.user.$.otherinformation"]

基本上,无论我在哪里看到.$. ,我需要保留它,然后在 .$. 出现之前附加所有内容以及.$发生之前的一切

示例:

difference.$.user.$.otherinformation应该被解析为包含:

difference
difference.$
difference.$.user
difference.$.user.$
difference.$.user.$.otherinformation

我强烈认为这里涉及某种递归,但尚未朝那个方向发展。

下面是我的实现,但不幸的是,当我的子字符串匹配第一次出现的 .$. 时, 它停止并且不继续检查其他出现的 .$.在同一个字符串中。

我怎样才能最好地结束它?

当前有缺陷的实现:

for(var i=0; i<array.length; i++){
    //  next, replace all array field references with $ as that is what autoform's pick() requires
    //  /\.\d+\./g,".$." ==> replace globally .[number]. with .$.    
    array[i] = array[i].replace(/\.\d+\./g,".$.");
        if(array[i].substring(0, array[i].lastIndexOf('.$.'))){
            console.log("Substring without .$.  " + array[i].substring(0, array[i].indexOf('.$.')));
            console.log("Substring with .$ " + array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')));
            }
        }
    // finally remove any duplicates if any
    array = _.uniq(array);

最佳答案

功能性单衬垫可以是;

var array  = ["authentication.$.order", "difference.$.user.$.otherinformation"],
    result = array.reduce((r,s) => r.concat(s.split(".").reduce((p,c,i) => p.concat(i ? p[p.length-1] + "." + c : c), [])), []);
console.log(result);

关于javascript - 在每次出现特定子字符串时剪切数组中存在的 JS 字符串并附加到同一数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44371515/

相关文章:

javascript - Google 应用程序脚本 : use the mailapp. sendmail 服务发送仅带有偶尔附件的邮件

javascript - Node.js Express 应用程序 : if cookie is present, 从服务器端向元素添加 CSS 类

javascript - 我在最后一个函数中的数字旁边得到 NaN

java - 不确定在这种情况下字符串拆分实际上是如何工作的

javascript - 在javascript中选择圆括号之间的文本

javascript - 无法使用 Travis CI 安装 Phoenix 框架 npm 依赖项(phoenix 和 phoenix_html)

C++文本文件转化为多维数组问题

javascript - JavaScript 中的Reduce 方法

c - 具有良好字符串操作支持的可嵌入语言

string - 返回 List<String> 的命名查询