简体   繁体   中英

Recreate an array from the existing array in Javascript

I have an array of strings in javascript. I want to join the elements and create a single string. Now at a particular length, I want to divide the string (say in 3 parts) and create a new array with 3 elements.

firstArray = [
        'Hello, this is line one of the array sentence',
        'Hello, this is line two of the array sentance'
      ];
// Output - secondArray = ["Hello, this is line one of"," the array sentence Hello, this is","line two of the array sentance"]

You can use the match function:

 var firstArray = [ "Hi this is a very very very long string, that", "is meant to be broken down every 10 or 15 characters" ]; // First join the first array var joinedArray = firstArray.join(""); // Split in chunks of 10 var tenChunksArray = joinedArray.match(/.{1,10}/g); console.log(tenChunksArray); // Split in chunks of 15 var fifteenChunksArray = joinedArray.match(/.{1,15}/g); console.log(fifteenChunksArray);

You need to join your arrays into one, then divide it into digits and split into chunks. Eg

const inputArr = [
  'Hello, this is line one of the array sentence',
  'Hello, this is line one of the array sentence',
];

const resplitArray = (arr, chunkSize) => {
  const res = [];
  const charsArr = arr.join(' ').split('');
  for (let i = 0, j = charsArr.length; i < j; i += chunkSize) {
    res.push(charsArr.slice(i, i + chunkSize).join(''));
  }
  return res;
};

console.log(resplitArray(inputArr, 10));

Update: I like the variant with regex match better

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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