Home > OS >  How do I skip items in array if value is 0
How do I skip items in array if value is 0

Time:01-25

Let's say I have an array of scores:

const scores = [20, 0, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]; 

By default, I'm displaying current month's score (scores[0]) and previous month's score (scores[1]).

If previous month is 0, I want to display the last index with a value that isn't zero. (scores[2] in this instance). Meaning is we have 0 values from index 1 to 8, I want to display index 9 as previous month's score

for (let i = 0; i < scores.length; i  ) {
  if (scores[i] === 0) {
    // At this point I want to skip to the next index.
    // If the next index is also zero, I skip till I get an index with a value
  }
}

CodePudding user response:

You simply need to use the continue statement, just like this:

const scores = [20, 0, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]; 
for (let i = 0; i < scores.length; i  ) {
    if (scores[i] === 0) {
        continue;
    }
    // do stuff
}

CodePudding user response:

You can use Array#find to get the first non-zero element.

let res = scores.find((x, i) => i && x !== 0);

CodePudding user response:

You should use continue which basically skips to the next iteration so your code will look something like this:

for (let i = 0; i < scores.length; i  ) {
  if (scores[i] === 0) {
    continue;
  }
}

CodePudding user response:

If you want to the the first non-zero value, just locate the first index starting at 0. After you find that value, search for the next value that follows that index.

const fromIndex = (callbackFn, fromIndex) =>
  (element, index, array) =>
    index >= fromIndex && callbackFn(element, index, array);

const getBreakdown = (scores, criteria) => {
  const currentIndex = scores.findIndex(criteria);
  const previousIndex = scores.findIndex(fromIndex(criteria, currentIndex   1));
  return {
    current: scores[currentIndex],
    previous: scores[previousIndex],
  };
};

const
  scores = [20, 0, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120],
  breakdown = getBreakdown(scores, (score) => score > 0);

console.log(breakdown);

Alternatively, you could always filter non-zero values:

const getBreakdown = (scores, criteria) => {
  const [current, previous] = scores.filter(criteria);
  return { current, previous };
};

const
  scores = [20, 0, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120],
  breakdown = getBreakdown(scores, (score) => score > 0);

console.log(breakdown);

  • Related