“algoritma filter javascript di tempat” Kode Jawaban

algoritma filter javascript di tempat

function filterInPlace(a, condition) {
  let i = 0, j = 0;

  while (i < a.length) {
    const val = a[i];
    if (condition(val, i, a)) a[j++] = val;
    i++;
  }

  a.length = j;
  return a;
}
Outrageous Opossum

algoritma filter javascript di tempat

function filterInPlace(a, condition, thisArg) {
  let j = 0;

  a.forEach((e, i) => { 
    if (condition.call(thisArg, e, i, a)) {
      if (i!==j) a[j] = e; 
      j++;
    }
  });

  a.length = j;
  return a;
}

a = [ 1,, 3 ];
document.write('<br>[',a,']');

filterInPlace(a, x=>true);
document.write('<br>[',a,'] compaction when nothing changed');

b = [ 1,,3,,5 ];
document.write('<br>[',b,']');

filterInPlace(b, x=>x!==5);
document.write('<br>[',b,'] with 5 removed');
 Run code snippet
Outrageous Opossum

Jawaban yang mirip dengan “algoritma filter javascript di tempat”

Pertanyaan yang mirip dengan “algoritma filter javascript di tempat”

Lebih banyak jawaban terkait untuk “algoritma filter javascript di tempat” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya