最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Merge every 3 elements in array javascript - Stack Overflow

programmeradmin1浏览0评论

I'm new to programming, and would appreciate any help.

Suppose I have the following array. (Note that this array prises of 6 elements)

var data = 
[
  'he' ,
  'l' ,
  'lo',
  'th',
  'e',
  're',

]

My goal here, is to either to create a new array that joins every three elements, into a single element.

Currently, my novice approach to this problem, is to use a simple for loop, to take each element, and add the index of the element +1 and the index of the element + 2 to the initial element.

The code seems to work partially, but since it iterates through each element and not every 3, it joins the elements too many times.

Here is my code:


var data = 
[
  'he' ,
  'l' ,
  'lo',
  'th',
  'e',
  're',

]

var newdata = []
        for (var i = 0; i < data.length; i++) {
 var three = data[i] + data[i+1] + data[i+2]
 newdata.push(three)

}
console.log(newdata) // => This will output  'hello', 'lloth' 'lothe' 'there' 'ereundefined' 'reundefinedundefined'

The desired output is this:

var data = 
[
'hello',
'there',
]

To get this existing code working, I assume I would have to delete the element + element +1 and element + 2, so that it doesn't join things unnecessarily the correctly, but I've had no success with that.

I'm open to other solutions/alternates that get the same output.

Any help is highly appreciated.

I'm new to programming, and would appreciate any help.

Suppose I have the following array. (Note that this array prises of 6 elements)

var data = 
[
  'he' ,
  'l' ,
  'lo',
  'th',
  'e',
  're',

]

My goal here, is to either to create a new array that joins every three elements, into a single element.

Currently, my novice approach to this problem, is to use a simple for loop, to take each element, and add the index of the element +1 and the index of the element + 2 to the initial element.

The code seems to work partially, but since it iterates through each element and not every 3, it joins the elements too many times.

Here is my code:


var data = 
[
  'he' ,
  'l' ,
  'lo',
  'th',
  'e',
  're',

]

var newdata = []
        for (var i = 0; i < data.length; i++) {
 var three = data[i] + data[i+1] + data[i+2]
 newdata.push(three)

}
console.log(newdata) // => This will output  'hello', 'lloth' 'lothe' 'there' 'ereundefined' 'reundefinedundefined'

The desired output is this:

var data = 
[
'hello',
'there',
]

To get this existing code working, I assume I would have to delete the element + element +1 and element + 2, so that it doesn't join things unnecessarily the correctly, but I've had no success with that.

I'm open to other solutions/alternates that get the same output.

Any help is highly appreciated.

Share Improve this question edited Aug 18, 2020 at 5:21 Lucaso12 asked Aug 18, 2020 at 5:13 Lucaso12Lucaso12 691 silver badge6 bronze badges 4
  • 3 Change your for loop increment to 3 i.e. for (var i = 0; i < data.length; i+=3) { – Nick Commented Aug 18, 2020 at 5:17
  • Note you have a typo in the question, var three = data[i] + data[i+1] + data[i+1] should be var three = data[i] + data[i+1] + data[i+2] – Nick Commented Aug 18, 2020 at 5:18
  • when you use i++ i will be incremented by one each loop. If you use i+=3 i will be incremented by 3 each loop. Another error is, that you used data[i+1] twice, the second one should be i+2. – Starbax Commented Aug 18, 2020 at 5:19
  • @Starbax I added i+2 initally, weird. Thanks for the tip, it works! – Lucaso12 Commented Aug 18, 2020 at 5:20
Add a ment  | 

7 Answers 7

Reset to default 4

const data = 
[
  'he' ,
  'l' ,
  'lo',
  'th',
  'e',
  're',
]
const newdata = []
for (let i = 0; i < data.length; i+=3) { // i+=3 can solve your problem
  const three = data[i] + data[i+1] + data[i+2]
  newdata.push(three)
}
console.log(newdata)

Change your code to

const data =
    [
        'he',
        'l',
        'lo',
        'th',
        'e',
        're',

    ]

const newdata = []
while (data.length){
    newdata.push(data.splice(0,3).join(''))
}
console.log(newdata)

You could also use the reduce method for your task:

const output = ["he", "l", "lo", "th", "e", "re"].reduce((acc, next, index) => {
  if (index % 3 === 0) { // if index is 0, 3, 6, 9, ...
    acc.push(next);
  } else { // if not, append to the last element
    acc[acc.length - 1] = acc[acc.length - 1] + next;
  }

  return acc;
}, []);

console.log(output)

returns

(2) ["hello", "there"]

While we can do this with for or while loops, a solution not mentioned in other answers is to use a reducer, which allows us to perform this trick as an new assignment, similar to how you use map:

const data = [1,2,3,4,5,6,7,8,9,10,11,12];
const chunkSize = 3;
const chunked = data.reduce((result,_,i) => {
                  const s = data.slice(chunkSize * i,chunkSize * (i+1));
                  if (s.length) result.push(s);
                  return result;
                }, []);

console.log(chunked);

In this reducer, we don't actually care about "the elements themselves", we just care about what index we're on, so we can generate slice(0,3) for the first element, slice(4,6) for the second element, etc. and at some point our slices will be empty so we just ignore those.

And because we're using slice, if we have an unbalanced number of elements, we don't end up creating arrays with length 3 don't actually contain 3 elements because they're padded with undefined entries.

And of course, we can even make the reducer itself something we generate for a specific chunkSize, so we can stick that in some utils.js and just import it where needed.

function sliceReducer(data, chunkSize) {
  return function(result,_,i) {
    const s = data.slice(chunkSize * i,chunkSize * (i+1));
    if (s.length) result.push(s);
    return result;
  };
}

const input = [1,2,3,4,5,6,7,8,9,10,11,12];
const chunked = input.reduce(sliceReducer(input, 5), []);

console.log(chunked);

The .slice() method is really helpful here, as it leaves the original array intact and creates a new array based on the indexes provided to it. Then we just iterate over every 3 arrays by incrementing 'i' by 3 every time and add each slice to the array to put it all together.

const joinEveryThree = () => {
  let data = ["he", "l", "lo", "th", "e", "re"];
  let newData = [];
  for (let i = 0; i < data.length; i += 3) {
    let chunk = data.slice(i, i+3);
    newData.push(chunk.join(''))
  }
  return newData.join(' ')
};

You were already very close to the solution. If you don't want to edit the original array, all you need to do is increment the index by 3 instead of 1, and modify the conditional so that if the length of the array isn't a product of 3 you don't get an error:

for (var i = 0; i + 2 < data.length; i += 3) {
  newData.push(data[i] + data[i + 1] + data[i + 2]);
}

If there are one or two extra items at the end of your array, this will ignore them.

const data = ["he", "l", "lo", "th", "e", "re"];
const size = 3;
const newData=new Array(Math.ceil(data .length / size ))
    .fill()
    .map((_, i) => data .slice(i * size , i * size  + size ))
    .map(data => data.join('')).join(' ')
console.log(newData)
发布评论

评论列表(0)

  1. 暂无评论