简体   繁体   English

在每个第 n 个索引处连接两个相邻数组元素的最佳方法

[英]Best way to join two adjacent array elements at each nth index

Assuming the following array example:假设以下数组示例:

const arr = ['mango', 'apple', 'kiwi', 'melon', 'orange', 'banana']

how do I convert it to look like this:我如何将其转换为如下所示:

const result = ['mango apple', 'kiwi', 'melon orange', 'banana']

I've tried with a foor loop, but I'm unsure of the algorithm in the if condition or if it's even the best way, or perhaps reduce is better?我试过 foo 循环,但我不确定 if 条件下的算法,或者它是否是最好的方法,或者 reduce 更好?

 const arr = ['mango', 'apple', 'kiwi', 'melon', 'orange', 'banana'] let n = [] for (let i = 0; i < arr.length; i++ ) { //Something like simply: i % 2 == 0 //Is obviously not good enough if (/* What here?*/) { n.push(arr[i] + ' ' + arr[i+1]) } else { n.push(arr[i]) } }

You can use modulus ( % ) for this, here is an example:您可以为此使用模数( % ),这是一个示例:

 var arr = ['mango', 'apple', 'kiwi', 'melon', 'orange', 'banana']; var result = []; for (let i = 0; i < arr.length; i++) { if (i % 3 == 0 && i + 1 < arr.length) { result.push(`${arr[i]} ${arr[i + 1]}`); i++; } else { result.push(arr[i]); } } console.log(result);

One way of doing this is like this:这样做的一种方法是这样的:

 const arr = ['mango', 'apple', 'kiwi', 'melon', 'orange', 'banana', 1, 2 ,3, 4, 5, 6] let n = [] for (let i = 0; i < arr.length; i+=3 ) { n.push(arr[i] + ' ' + arr[i+1]); n.push(arr[i+2]); } console.log(n); // output // ["mango apple", "kiwi", "melon orange", "banana", "1 2", 3, "4 5", 6]

EDIT: As per Shiva's comment, I have modified code to handle out of index values编辑:根据 Shiva 的评论,我修改了代码以处理索引值

const arr = ['mango', 'apple', 'kiwi', 'melon']
let n = []
for (let i = 0; i < arr.length; i+=3 ) {
    if(arr[i] === undefined) {
        break;
    }

    let first = arr[i];
    if(arr[i+1] !== undefined) {
        first+= ' ' + arr[i+1];
    }
    n.push(first);
    if(arr[i+2] !== undefined) {
        n.push(arr[i+2]);
    }
}
console.log(n);
// output
// ["mango apple", "kiwi", "melon"]

You could take an offset for getting the real index i + offset and iterate a virtual index i for getting the check done.您可以采用offset来获取实际索引i + offset并迭代虚拟索引i以完成检查。

 var array = ['mango', 'apple', 'kiwi', 'melon', 'orange', 'banana'], n = 2, offset = 0, result = []; for (let i = 0; i + offset < array.length; i++) { result.push(i % n == 0 ? array[i + offset] + ' ' + array[i + 1 + offset++] : array[i + offset] ); } console.log(result);

An approach with a generator function.一种具有生成器功能的方法。

 function* getNTh(array, n) { var i = 0, offset = 0; while (i + offset < array.length) { yield i % n == 0 ? array[i + offset] + ' ' + array[i + 1 + offset++] : array[i + offset]; i++; } } console.log([...getNTh(['mango', 'apple', 'kiwi', 'melon', 'orange', 'banana'], 2)]); console.log([...getNTh(['mango', 'apple', 'kiwi', 'melon', 'orange', 'banana'], 3)]);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

I'm a big fan of re-using code.我是重用代码的忠实粉丝。 IOW: I'm a lazy programmer. IOW:我是一个懒惰的程序员。 :) :)

As such from what I can gather the OP is really after a pattern iterator.因此,从我可以收集到的 OP 确实是在模式迭代器之后。 Because something like this might be useful for the future this is something I'd try and generalise and make into a function.因为这样的事情可能对未来有用,所以我会尝试将其概括为一个函数。

With this in mind, I'm a big fan of the new Javascript feature called Iterators and generators.考虑到这一点,我非常喜欢称为迭代器和生成器的新 Javascript 功能。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators and this problems seems to fit nicely here for something that could get re-used again & again. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators并且这个问题似乎很适合这里的东西,可以一次又一次地重复使用。

ps.附: Even if you want to target browsers that don't have generators yet, save yourself a life of misery and get your Javscript transpiled.即使您想针对还没有生成器的浏览器,也要避免痛苦并让您的 Javscript 转译。 Most modern browsers already have good support too -> https://caniuse.com/#feat=es6-generators大多数现代浏览器也已经有了很好的支持 -> https://caniuse.com/#feat=es6-generators

Below is an example, and you can see how easy it is then to change the pattern, without having to worry about modulus & stepping etc.下面是一个例子,你可以看到改变模式是多么容易,而不必担心模数和步进等。

 function *patternIter(pattern, len) { let p = 0, ps = pattern[p], c; for (l = 0; l < len; l += 1) { if (!c) c = {offset: l, size: 0}; c.size += 1; if (c.size === ps) { yield c; c = undefined; p += 1; ps = pattern[p % pattern.length]; } } if (c) yield c; } const arr = ['mango', 'apple', 'kiwi', 'melon', 'orange', 'banana'] function showPattern(p) { console.log('Pattern ' + p.join(", ")); console.log( [...patternIter(p, arr.length)] .map(m => arr.slice(m.offset, m.offset + m.size) .join(" ")).join(", ") ); } showPattern([1, 2]); showPattern([3, 2, 1]); showPattern([1, 3, 2]); showPattern([3, 1]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM