JS — spread Array, isArray(),filter,match,map,replace, regex

#spread Array

cities.push(...data);

#isArray() — return true or false

console.log(Array.isArray(cities))

#map — creates a new array with the results of calling a provided function on every element in the calling array.

array.map(function(value,index{
}))

#filter — create new Array — returns an array

  • filter(callback(value,index)) — 걸러내다
  • undefined가 포함된 array를 아래와 같이 filter 할 경우 ,
  • undefined, null, 빈값은 제외하고 값만 반환시킨다.
var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];

/**
* Array filters items based on search criteria (query)
*/
function filterItems(query) {
return fruits.filter(function(el) {
return el.toLowerCase().indexOf(query.toLowerCase()) > -1;
})
}

console.log(filterItems('ap')); // ['apple', 'grapes']
var ages = [32, 33, 16, undefined];function checkAdult(age) {
return !!age;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.filter(checkAdult); // 32,32,16
}

#match-string.match

var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var regexp = /[A-E]/gi;
var matches_array = str.match(regexp);

console.log(matches_array);
// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']

# the difference between filter and map

// Say I have
var array = [1, 2, 3, 4, 5, 6];

// I can use `filter` to get an array of just odd numbers:
var odds = array.filter(function(entry) { return entry % 2 == 1; });
console.log("odds: " + odds);

// I can use `map` to get an array of those numbers doubled:
var doubles = array.map(function(entry) { return entry * 2; });
console.log("doubles: " + doubles);
  • filter returns an new array of skip unwanted elements of collection ( 원하지 않는 대상 제외, 비교 조건 검사, 문자비교)
  • map returns an new array of modifying elements of collection.
  • What is different is that expects that function to return Boolean value based on which element will be skipped or not. will expect that function to return an new collection element.

#replace- string.replace

str.replace(regexp|substr, newSubstr|function)
var str = "Mr Blue has a blue house and a blue car";
var res = str.replace(/blue/g, "red");
//Regexvar re = /ab+c/;orvar re = new RegExp('ab+c');

#ref

https://stackoverflow.com/questions/43693000/what-is-the-difference-between-filter-and-map-in-jquery