B
B
biz532021-07-07 13:59:15
JavaScript
biz53, 2021-07-07 13:59:15

How to optimize work with an array?

You need to write the optimal code (in terms of speed), which will return the modified array according to the following parameters.
Given:
- an array of n elements
Input:
- list (array)
- startIndex (where to get it from)
- endIndex (where to put it)
Output:
- modified array, where startIndex is replaced by endIndex

There is such code, but it sometimes takes about 2 seconds ( which is very slow, despite the fact that there are no more than 100 elements (just objects without arrays and objects inside, only key - value) in the array)

const reorder = (list, startIndex, endIndex) => {
    const result = Array.from(list);
    const [removed] = result.splice(startIndex, 1);
    result.splice(endIndex, 0, removed);
  
    return result;
  }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question