簡體   English   中英

如何在 JavaScript 中操作數組中所有特定字符串值的每個實例?

[英]How can I manipulate each instance of all specific string values within an array in JavaScript?

對於特定字符串的每個實例,我想返回一個新數組。 假設我有一個如下所示的字符串數組。

let stringArr = ["when", "the", "like", "because", "the", "apple" "like", "the", "star"]

我最終得到的是每個 str 的新數組,其中包括該字符串的每個實例之后的字符串。 例如:

var whenArray = ["the"]

var theArray = ["like", "apple"]

var likeArray = ["because", "the"]

var becauseArray = ["the"]

var appleArray = ["like"]

var starArray = []

在字符串the每個實例之后,我們會看到字符串likeapple 字符串的每個實例之后like ,我們看到的likethe

像這樣的東西?

 let strings = ["when", "the", "like", "because", "the", "apple", "like", "the", "star"]; const output = {}; for (let i = 0; i < strings.length; i++) { if (!output[strings[i]]) { output[strings[i]] = []; } if (i + 1 < strings.length) { output[strings[i]].push(strings[i + 1]); } } console.log(output);

let strArr = ["when", "the", "like", "because", "the", "apple", "like", "the", "star"];

function nextArrs(strArr) {
    return strArr.reduce((acc, curr, idx, arr) => {
        let arrName = curr + 'Array';
        if (!acc.hasOwnProperty(arrName)) {
            acc[arrName] = [];
        }
        if (arr[idx + 1] !== undefined) {
            acc[arrName].push(arr[idx + 1]);
        }
        return acc;
    }, {});
}

console.log(nextArrs(strArr));

 let stringArr = ["when", "the", "like", "because", "the", "apple", "like", "the", "star"]; function findNextElementArray(arr){ return arr.map(function(query, i){ return {[query]: stringArr.map(function(item, index){ return (item === query ? (stringArr[index+1] ? stringArr[index+1]: false): false); }).filter(function(item){ return item !== false }) } }); } console.log(findNextElementArray(stringArr));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM