filter method array javascript code example

Example 1: filter javascript array

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);

Example 2: array.filter in javascript

//Eg 1 - If item is unchecked, remove it from array

const array = [2, 3, 4]

if (event.target.checked) {
      newValue.push(option);
    } else {
      newValue = newValue.filter(item => item.id != option.id);
    }

//If false, it will remove the element. 2 is not equal to 2.

//Eg 2 - To return an array with length > 6

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);

Example 3: filter items javascript

// Filter items
function filterItems(e) {
  // Convert to lowercase
  var text = e.target.value.toLowerCase();
  // Get lis
  var items = itemList.getElementsByTagName('li');
  // Convert to an array
  Array.from(items).forEach(function(item) {
    var itemName = item.firstChild.textContent;
    if (itemName.toLowerCase().indexOf(text) != -1) {
      item.style.display = 'block';
    } else {
      item.style.display = 'none';
    }
  });
}

Example 4: does filter change original array

Note: filter() does not change the original array.