Search code examples
javascriptarraysfor-loopsplice

Iterate over Array and replacing at a certain value


I have a question about feasibility of my code. I'm sure there is a better and more efficient way to write the function I wrote.

This is the function:

let i;
for (i = 0; i < ns.length; i++) {
  if (ns[i] > 1) {
    ns[i] = 3;
    const place = ns[i];
    ns.splice(place + 2, 1, 4);
    ns.splice(place, 1, 2);
    ns.splice(place - 1, 1, 1);
  }
}

Initial Array (this array have a length of upto 20 items):

ns = [1 , 1 , 1 , 1 , 2 , 0]

Result Array:

ns = [1 , 1 , 1 , 2 , 3 , 4]

Believe it or not but this will suit my needs. But is there a better way than to just add up three times splice? It also extends my array if the number two of the initial array is at the end or beginning. I know I could just wrap it in another conditional but this seems so clumsy to me.


Thanks in Advance!
Regards


Solution

  • So with help from Nina Scholz and a Friend i got to the right answer:

    Initial Array:

    ["1", "1", "1", "1", "1", "2", "0", "0"]
    

    Desired Array:

    ["1", "1", "1", "1", "2", "3", "4", "0"]
    

    The Function:

       isSibling() {
        const siblings = this.props.data.map(item => (
          item.progress
        ));
        let i;
        const place = '3';
        for (i = 0; i < siblings.length; i++) {
          if (siblings[i] === '2') {
            const num = i;
            siblings[i] = place;
            this.update(siblings, i - 1, '2');
            this.update(siblings, i + 1, '4');
            return siblings;
          }
        }
        return siblings;
       }
    

    Update Function:
    to ensure the array is not enlongated or shortened:

      update(array, index, value) {
        if (index >= 0 && index < array.length) {
          array[index] = value;
        }
      }
    

    Thank you for your help! :D