在数组内所有元素之间插入值的功能方法

时间:2019-01-15 12:02:07

标签: javascript arrays functional-programming

假设我有以下数组:

const myArray = ["q", "w", "e", "r", "t", "y"]

我想做的是在所有元素之间添加一个元素,如下所示:

myArray.someMethod("XXX")
// ["q", "XXX", "w", "XXX", "e", "XXX", "r", "XXX", "t", "XXX", "y"]

从某种意义上讲,.join的作用很强,但是我希望输出是另一个数组,而不是字符串。

我知道如何通过循环执行此操作,但是我想知道是实现此目标的“功能性”方法。

6 个答案:

答案 0 :(得分:6)

代替迭代方法,可以采用递归方法,方法是使用剩余参数并检查剩余数组的长度。

<build>
    <plugins>
        <plugin>
            <groupId>org.eclipse.tycho</groupId>
            <artifactId>tycho-p2-director-plugin</artifactId>
            <version>${tycho-version}</version>
            <executions>
                <execution>
                    <id>create-distributions</id>
                    <goals>
                        <goal>materialize-products</goal>
                        <goal>archive-products</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
const
    zip = ([a, ...r], v) => r.length ? [a, v, ...zip(r, v)] : [a];

console.log(zip(["q", "w", "e", "r", "t", "y"], 'XXX'));

答案 1 :(得分:4)

以函数式编程方式,数组是Monad,这意味着它是flatMappable的。 FlatMap是Monadic绑定运算符的实现,该运算符对于Array,它将元素映射到新数组并将它们展平在一起。

有了这个主意,您只需要在flatMap函数内的输出数组中添加一个新值。请参阅以下

Array.prototype.someMethod = function(a){ return this.flatMap(i => [i,a]) }

myArray.someMethod("XXX")
// Array(12) [ "q", "XXX", "w", "XXX", "e", "XXX", "r", "XXX", "t", "XXX", … ]

上面的示例在数组的末尾添加了XXX,因此我们可以通过如下使用flatMap的index参数来忽略最后一个元素的填充

Array.prototype.someMethod = function(a){ let L=this.length; return this.flatMap((n,i) => (i<L-1) ? [n,a] : [n]) }

myArray.someMethod("XXX")
// Array(11) [ "q", "XXX", "w", "XXX", "e", "XXX", "r", "XXX", "t", "XXX", "y"]

答案 2 :(得分:1)

您可以将.map().concat()一起使用:

const data = ["q", "w", "e", "r", "t", "y"];
const str = "XXX";

const insertValue = (arr, val) => [].concat(
    ...arr.map((v, i) => (i > 0 ? [str, v] : v))
);

console.log(insertValue(data, str));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 3 :(得分:0)

const myArray = ["q", "w", "e", "r", "t", "y"]
const joinStr = 'xxx';
console.log(myArray.join(','+ joinStr + ',').split(','));

答案 4 :(得分:0)

您可以将map()与flat()一起使用

const myArray = ["q", "w", "e", "r", "t", "y"];
const newArray = myArray.map((i) => {
   return [i, 'xxx']
}).flat();

console.log(newArray);

答案 5 :(得分:0)

您可以使用reduce来转换原始数组,然后将其放入两个参数函数中,或者将其添加为Array.prototype的方法(如果您确实希望在帖子中使用call方法):

const myArray = ["q", "w", "e", "r", "t", "y"]

// A function taking array and glue arguments

const interpose = (array, glue) => array.reduce(
   (acc, c,i,a) => (
        acc.push(c) && (i < a.length -1) && acc.push( glue),
        acc
    ), []
);

// As an array method

Array.prototype.interpose = function( glue) {
    return  this.reduce(
    (acc, c,i,a) => (
         acc.push(c) && (i < a.length -1) && acc.push( glue),
         acc
     ), []);
}

// Test

console.log( 'interpose( myArray, "XXX" = %s', interpose( myArray, "XXX"));
console.log( 'myArray.interpose("XXX")  = %s', myArray.interpose("XXX"));