Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

javascript filter in place algorithm

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;
}
Comment

javascript filter in place algorithm

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
Comment

PREVIOUS NEXT
Code Example
Javascript :: Membuat contact di google contact dengan google app script, sync ke android. 
Javascript :: onclick clear input field javascript 
Javascript :: vuejs bus.emit 2 times 
Javascript :: form handling in next js 
Javascript :: using for loops to add an event listener 
Javascript :: array.includes is not a function react 
Javascript :: jquery textfill example 
Javascript :: There is only one value in JavaScript that is not equal to itself, and that is NaN (“not a number”). 
Javascript :: Scotch.io - Create a CRUD App with Node and MongoDB 1 Getting Started 
Javascript :: how to generate password hash and a salt in nodejs 
Javascript :: desc sorting in array of objects javascript 
Javascript :: javascript call function from event handler es6 
Javascript :: vanilla javascript event when reach bottom of element no jquery 
Javascript :: nodejs sqlite3 db. insert 
Javascript :: seperate array by comma in vue 
Javascript :: waiting for the value from use effect 
Javascript :: create a friend component react js 
Javascript :: jQuery - The noConflict() Method 
Javascript :: Get JSON Values In Array Alternative Syntax 
Javascript :: jquery init dropdown 
Javascript :: video link on videojs 
Javascript :: javascript code for adding scroll to top of page 
Javascript :: _.isEqual Underscore Example 
Javascript :: Comparing mongoose _id and strings 
Javascript :: Use a stack to convert the infix expression x*y-2 into post-fix 
Javascript :: populate strapi v4 
Javascript :: context 
Javascript :: cocos creator localstorage 
Javascript :: left join in javascript 
Javascript :: pass function name as string javascript 
ADD CONTENT
Topic
Content
Source link
Name
3+7 =