HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Removing numbers from the middle of an array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theremovingarraynumbersfrommiddle

Problem

I have an array like this (make sure you scroll to the right):

[0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0]


Where it will always be the same length. And there will always be some number of 0's surrounding some number of 1's. I am trying to find a good/efficient/smart way to turn the middle of the array of into 0's when there is a padding of 4 1's on each side. The result would be something like:

[0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0]


Where you now have a padding of 4 1's on either side.

This is how I implemented it:

var a = [0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0];

var hitOne = false;
var oneCount = 0;
var oneStopPoint = a.lastIndexOf(1) - 3;
for(var n in a){
    if(n == oneStopPoint){
        break;   
    }
    if(a[n] == 1 && !hitOne) {
        hitOne = true
        oneCount++;
    } else if(a[n] == 1 && hitOne) {
        oneCount++;
    }
    if(oneCount > 4){
        a[n] = 0;
    }
}
console.log(a);


http://jsfiddle.net/4gk9L9uv/1/

Solution

Firstly: Don't use for...in on arrays.

Secondly, I suppose you can find the 1-boundaries, and add/subtract 4:

var left = array.indexOf(1) + 4;
var right = array.lastIndexOf(1) - 4;
for(; left <= right ; left++) {
  array[left] = 0;
}


Not particularly clever, but it does the job.

(Note: lastIndexOf is widely supported in modern runtimes, but older ones may not have it)

But also take @itsbruce's advice from the comments, and consider another structure for these data.

Code Snippets

var left = array.indexOf(1) + 4;
var right = array.lastIndexOf(1) - 4;
for(; left <= right ; left++) {
  array[left] = 0;
}

Context

StackExchange Code Review Q#71732, answer score: 5

Revisions (0)

No revisions yet.