0

I have two list x_values and y_values such as :

x_values = [x1, x2, ...., xN];
y_values = [y1, y2, ...., yN];

I would like to create a list result such as :

result = [[x1, y1], [x2, y2], .... [xN, yN]]

Currently I am doing the following :

let result = [];

// Format new data
for (let j = 0; j < x_values.length; j++) {
   result.push([x_values[j], y_values[j]]);
}

This is working, but when N is very high, this script is really slow (I need to execute it multiple times per second)

Do you have any way to accelerate the generation of this list ?

Thanks :)

graille
  • 1,131
  • 2
  • 14
  • 33
  • 1
    Just an FYI, this is typically referred to as "zipping". You may be able to find information by searching that. – Carcigenicate Jan 13 '20 at 00:52
  • To get your result, you need to visit all values from `x` once, and all values from `y` once. So, the minimum possible iterations would be `N`. With that in mind, this is already quite optimized. Unless there is a method faster than `.push()` for arrays, but I doubt that would affect your runtime drastically. – Nick Parsons Jan 13 '20 at 00:55
  • 2
    the short answer is that, no, there isn't really anything faster than a straight up immediate for loop, although you _can_ speed it up by tracking the index it needs to go at and directly assigning (`result[pos] = ...`) rather than using push. The *real* question is: why in the world do you need to run this "multiple times per second"? That sounds like you're probably doing something very wrong in terms of the data you're working with. – Mike 'Pomax' Kamermans Jan 13 '20 at 00:56

2 Answers2

1

Use the map method:

var a = ['a1', 'a2', 'a3']
var b = ['b1', 'b2', 'b3']
var c = a.map(function(e, i) {
 return [e, b[i]];
});

As mentioned here.

The time complexity of this function is also "O(n)". Not sure if there is a faster way to do it. If the idea is to access the information in the 2 lists later on in the code you could just keep these lists the way they are and then just access the index directly as needed. That could make your list processing faster as the time complexity of accessing the list would then be O(1)

1

One thing you can do is to use index instead of push. Another thing is to create the result array with a given length first. Here is a benchmark comparison.

let result = new Array(x_values.length);
for (let j = 0; j < x_values.length; j++) {
   result[j] = [x_values[j], y_values[j]];
}

Also, Array.forEach and Array.map are definitely slower than for-loops. This is due to the fact that they construct a new context (this, local namespace, etc) every time the function passed to them is called. Functional programming in JS often makes code cleaner at the cost of performance.

Hurried-Helpful
  • 1,850
  • 5
  • 15