使用for循环将数组组成一个数组。

huangapple go评论68阅读模式
英文:

Create groups of arrays into one array using for loop

问题

I have one lab where is given:
const names = ['Peter', 'Andrew', 'Ann', 'Mark', 'Josh', 'Sandra', 'Cris', 'Bernard', 'Takesi'];

It's required to create a function that will create an array containing other arrays with three names:

[['Peter', 'Andrew', 'Ann'], ['Mark', 'Josh', 'Sandra'], ['Cris', 'Bernard', 'Takesi']]

I did below and it gives me one array, as expected:

function sortByGroups() {
    let arr = [];
    for (let i = 0; i < names.length; i = i + 3) {
        for (let j = i; j < i + 3; j++) {
            if (j < i + 2) {
                arr += `${names[j]},`;
            } else {
                arr += `${names[j]}`;
            }
        }
        return arr.split(',');
    }
}
console.log(sortByGroups()); // ['Peter', 'Andrew', 'Ann']

But after, I don't know what to do to get the required result:

[['Peter', 'Andrew', 'Ann'], ['Mark', 'Josh', 'Sandra'], ['Cris', 'Bernard', 'Takesi']]

英文:

I have one lab where is given:
const names = [&#39;Peter&#39;, &#39;Andrew&#39;, &#39;Ann&#39;, &#39;Mark&#39;, &#39;Josh&#39;, &#39;Sandra&#39;, &#39;Cris&#39;, &#39;Bernard&#39;, &#39;Takesi&#39;];

It's required to create function that will create array which will contain other arrays with three names:

`[[&#39;Peter&#39;, &#39;Andrew&#39;, &#39;Ann&#39;], [&#39;Mark&#39;, &#39;Josh&#39;, &#39;Sandra&#39;], [&#39;Cris&#39;, &#39;Bernard&#39;, &#39;Takesi&#39;]]`

I did below and it gives me one array , as expected:

function sortByGroups() {
    let arr = [];
    for (let i = 0; i &lt; names.length; i = i + 3){
        for (let j = i; j &lt; i + 3; j++){
            if (j &lt; i + 2){
                arr += `${names[j]},`;
            } else {
                arr += `${names[j]}`;
            }
        }
        return arr.split(&#39;,&#39;)
    }
}
console.log(sortByGroups()); // [ &#39;Peter&#39;, &#39;Andrew&#39;, &#39;Ann&#39; ]

but after I don't know what to do to get the required result:
[[&#39;Peter&#39;, &#39;Andrew&#39;, &#39;Ann&#39;], [&#39;Mark&#39;, &#39;Josh&#39;, &#39;Sandra&#39;], [&#39;Cris&#39;, &#39;Bernard&#39;, &#39;Takesi&#39;]]

答案1

得分: 1

从一个整数列表 i=0,1,2 中,你可以获取元素 3i 到 3i+2

一个基于 for 循环的版本可能是这样的:

const names = ['Peter', 'Andrew', 'Ann', 'Mark', 'Josh', 'Sandra', 'Cris', 'Bernard', 'Takesi'];

const groupedNames = []
for(let j=0; j<Math.ceil(names.length); j+=3){
    groupedNames.push(names.slice(j,j+3))
}
console.log(groupedNames)

一个完全功能的方法在这里:

它首先创建整数列表,然后将条目映射到它:

const names = ['Peter', 'Andrew', 'Ann', 'Mark', 'Josh', 'Sandra', 'Cris', 'Bernard', 'Takesi'];

const groupedNames = Array(Math.ceil(names.length/3)).fill(0).map((_,i)=>names.slice(3*i,3*(i+1)))

console.log(groupedNames)
英文:

From a list of integers i=0,1,2, you can get elements 3i to 3i+2

A for-loop based version might be this:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const names = [&#39;Peter&#39;, &#39;Andrew&#39;, &#39;Ann&#39;, &#39;Mark&#39;, &#39;Josh&#39;, &#39;Sandra&#39;, &#39;Cris&#39;, &#39;Bernard&#39;, &#39;Takesi&#39;];

const groupedNames = []
for(let j=0; j&lt;Math.ceil(names.length); j+=3){
groupedNames.push(names.slice(j,j+3))
}
console.log(groupedNames)

<!-- end snippet -->

A fully functional approach is here

It creates the list of integers first, and then maps the entries into it.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const names = [&#39;Peter&#39;, &#39;Andrew&#39;, &#39;Ann&#39;, &#39;Mark&#39;, &#39;Josh&#39;, &#39;Sandra&#39;, &#39;Cris&#39;, &#39;Bernard&#39;, &#39;Takesi&#39;];

const groupedNames = Array(Math.ceil(names.length/3)).fill(0).map((_,i)=&gt;names.slice(3*i,3*(i+1)))

console.log(groupedNames)

<!-- end snippet -->

答案2

得分: 0

  • 我们正在遍历所有的名字,使用临时变量 lastUsedIndex 来存储上一组中插入的最后一个元素的值,并确保下一次当前索引应该大于 lastUserIndex
  • 值得注意的是,如果源数据中还有额外的元素,它将添加一个类似于 ['that data',undefined,undefined] 的分组。
const names = ['Peter', 'Andrew', 'Ann', 'Mark', 'Josh', 'Sandra', 'Cris', 'Bernard', 'Takesi'];
let lastUsedIndex = -1;
const groupedNames = [];
names.forEach((name, i) => {
  if (i > lastUsedIndex) {
    lastUsedIndex = i + 2;
    groupedNames.push([names[i], names[i + 1], names[i + 2]]);
  }
})

console.log(groupedNames);
英文:
  • We are looping through, all names, using temporary variable lastUsedIndex to store value of last element inserted in last group, and just making sure next time that current index should be greater than lastUserIndex.
  • One thing to note, if there will be another extra element in source data then it will add group like [&#39;that data&#39;,undefined,undefined].

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const names = [&#39;Peter&#39;, &#39;Andrew&#39;, &#39;Ann&#39;, &#39;Mark&#39;, &#39;Josh&#39;, &#39;Sandra&#39;, &#39;Cris&#39;, &#39;Bernard&#39;, &#39;Takesi&#39;];
let lastUsedIndex = -1;
const groupedNames = [];
names.forEach((name, i) =&gt; {
  if (i &gt; lastUsedIndex) {
    lastUsedIndex = i + 2;
    groupedNames.push([names[i], names[i + 1], names[i + 2]]);
  }
})

console.log(groupedNames);

<!-- end snippet -->

答案3

得分: 0

你可以使用 Array.reduce 来迭代并返回结果数组。

const names = ['Peter', 'Andrew', 'Ann', 'Mark', 'Josh', 'Sandra', 'Cris', 'Bernard', 'Takesi'];

const createGroups = (size) => names.reduce((prev, curr, ix) => {
    let arrIx = Math.floor(ix / size);
    prev[arrIx] = [...(prev[arrIx] || []), curr];
    return prev;
}, []);

console.log(createGroups(3));
英文:

You can use Array.reduce to iterate the return the resulting array.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const names = [&#39;Peter&#39;, &#39;Andrew&#39;, &#39;Ann&#39;, &#39;Mark&#39;, &#39;Josh&#39;, &#39;Sandra&#39;, &#39;Cris&#39;, &#39;Bernard&#39;, &#39;Takesi&#39;];

const createGroups = (size) =&gt; names.reduce((prev, curr, ix) =&gt; {
	let arrIx = Math.floor(ix / size);
	prev[arrIx] = [...(prev[arrIx] || []), curr];
  return prev;
}, []);

console.log(createGroups(3));

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年4月6日 22:23:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75950635.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定