Array Methods Practice

We will be practicing the Array methods

Student's Array Practice page's

Output in JsBin: Search string

Using String.indexOf().

returns: index of first occurrence (or) -1 if not found

/*
String.prototype.indexOf() SYNTAX
-----------------------------------
indexOf(searchString)
indexOf(searchString, position)
----------------------------------*/

//PRACTICE 1
console.log(
  "Mango".indexOf("n")
)
console.log(
  "Mango".indexOf("g")
)
console.log(
  "Mango".indexOf("ng")
)
console.log(
  "Mango".indexOf("ngo")
)
console.log(
  "Mango".indexOf("M")
)
console.log(
  "Mango".indexOf("Ma")
)
console.log(
  "Mango".indexOf("Maa") //-1
)
console.log(
  "Mango".indexOf("z")  //-1
)
console.log(
  "Mango".indexOf("Maz")  //-1
)

Get the search text from input field.

Using addEventListener()

SYNTAX:
addEventListener(eventType, listenerCallbackFn)
addEventListener(eventType, listenerCallbackFn, options)
addEventListener(eventType, listenerCallbackFn, useCapture)

returns: None Undefined

//PRACTICE 2
<input id="searchInput">
-------------------------
document.getElementById('searchInput')
  .addEventListener( "change", (event) => {
    console.log( 
      "Mango".indexOf( event.target.value )
    );
  });

Note: 'event' refers to the element event object (here it's <input>) 'event.target.value' gets the value inside the input object


Get the search text from input field. And filter for each String in the Array And output the filtered elements in HTML

Using Array.prototype.filter()

SYNTAX:
filter(callbackFn)
filter(callbackFn, thisArg)

callbackFn arguments
(element, index, array) => {}

returns: array containing just the elements that pass the test.

//PRACTICE 3
const arr = ["Banana", "Apple", "Mango", "Sapota"];

document.getElementById('outputDiv')
  .innerHTML = arr;
    
  document.getElementById('searchInput')
    .addEventListener( "change", (event) => {
    
      const filteredElm = arr.filter( (elm) => {
        return elm.indexOf(event.target.value) !== -1
        //indexOf returns -1 if string not found
        //if -1 comes, make it to return false, so the filter will skip that element.
      })
    
      document.getElementById('outputDiv')
        .innerHTML = filteredElm;
    });
Output in JsBin: Search string

Using Array.isArray() method.

returns: Boolean

let checkArray = (val) => {
    return Array.isArray(val);
}
console.log( checkArray([1, 2, 4, 0]) ); //true
console.log( checkArray("This is a text") ); //false

Using instanceof operator

returns: Boolean

let checkArray2 = (val) => val instanceof Array;

console.log( checkArray2([1,2,3]) ); //true
console.log( checkArray2("These are text") ); //false

Using checking the "Object.prototype.constructor" type

returns: A reference to the constructor function

Reference: MDN - Object.prototype.constructor

let checkArray3 = (val) => {
    //return "These are text".constructor; //function String() { [native code] }
    //return [1,2,3].constructor; //function Array() { [native code] }
    return val.constructor === Array
}

console.log( checkArray3([1,2,3]) ); //true
console.log( checkArray3("These are text") ); //false

Using toString and .call()

let isarray = (val) => {
    //console.log( toString ); //function toString() { [native code] }
    //console.log( toString.call() ); //"[object Undefined]"
    //console.log( toString.call(val) ); //"[object Array]"
    console.log( toString.call(val) === "[object Array]"); //true
}
isarray( [1, 2, 4, 0] ); //true
isarray( "This is a text" ); //false

Reference: Stackoverflow

The toString function for Object (the built-in type for objects) happens to return what type of object it is as a string with the format [object Type].

.call() is a function that lets you change the context of another function.

const groceries = ['banana', 'apple', 'peanuts'];

if (groceries.indexOf('banana')) {
    console.log('We have to buy bananas!');
} else {
    console.log(`We don't have to buy bananas!`);
}
// groceries.indexOf('banana') // 0

groceries.indexOf("banana") returns 0, which is a falsy value.
Since the condition in the if-statement is falsy, the code in the else block runs, and We don't have to buy bananas! gets logged.