0

I got an array which is a result from webscraping that comes like this:

array:
[
  'line1',
  'line2',
  'line3',
  'linen'..
]

I have to insert this data to MySQL. The thing is, each 10 lines of the array is one line of MySQL table.

So I have to join line1 to line10 - line11 to line20 and so on..

I tried to create a new array with keys each 10 iterations like this:

arrayFinal.push({
    key: counter,
    value: array[i]
});

But wasn't the results I expected.

How can achieve this?

  • Update:

Let's say this is the array (or object idk) that i recieve:

array: 
[
    'id',
    'name',
    'age',
    'address',
    'id',
    'name',
    'age',
    'address'
]

There's non key that identifies which field is which. I just put the fields like 'id' so you can understand. Now, i have to separate this array to insert into mysql. You see a pattern each 4 lines, right?

'insert into mysql (id, name, age, address) values ?'
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
ziad.ali
  • 321
  • 4
  • 20

3 Answers3

2

If you want to transform your input array into an array of objects where each object will hold each successive (id, name, age and address) combination, you can use a for loop with a step equal to 4 to read each 4 elements in a single object.

This is how should be your code:

for (var i = 0; i < array.length; i+=4) {
  result.push({
    id: array[i],
    name: array[i + 1],
    age: array[i + 2],
    address: array[i + 3],
  });
}

Demo:

This is a working Demo:

var array = [
  'id',
  'name',
  'age',
  'address',
  'id',
  'name',
  'age',
  'address'
];

var result = [];

for (var i = 0; i < array.length; i+=4) {
  result.push({
    id: array[i],
    name: array[i + 1],
    age: array[i + 2],
    address: array[i + 3],
  });
}

console.log(result);
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
1

You'll need to separate your Array into chunks of 10 and use them like this :

const list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30];

//Separate your Array into chunks of 10
let newArray = new Array(Math.ceil(list.length / 10)).fill().map((_,i) => list.slice(i*10,i*10+10));

//Go through your chunks
for(let chunk of newArray){
  //Do whatever you want with them
  console.log('insert into mysql (id, name, age, address, ...) values '+chunk.join(','));
}

In the variable newArray, there is now an array of 10-length arrays.
For more info, see Split array into chunks.

After that, all you need to do is go through this array and create your new String using Array#join

Zenoo
  • 12,670
  • 4
  • 45
  • 69
0

IF ONLY I guessed what you are looking for correct, below is the code:

let arrayFinal = [];
for (var i =0; i < array.length; i+10) {
  end = i + 10;
  end = array.length > end ? end : array.length;
  arrayFinal.push(array.slice(i, end));
}
UtkarshPramodGupta
  • 7,486
  • 7
  • 30
  • 54