英文:
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 = ['Peter', 'Andrew', 'Ann', 'Mark', 'Josh', 'Sandra', 'Cris', 'Bernard', 'Takesi'];
It's required to create function that will create array which will contain 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']]
答案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 = ['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)
<!-- 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 = ['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)
<!-- 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 thanlastUserIndex
. - One thing to note, if there will be another extra element in source data then it will add group like
['that data',undefined,undefined]
.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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);
<!-- 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 = ['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));
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论