第2週JS ALGORITHM STUDY



thisArg Parameter


Most methods support “thisArg”
Almost all array methods that call functions – like find, filter, map, with a notable exception of sort, accept an optional additional parameter thisArg.
Here’s the full syntax of these methods:
arr.filter(func, thisArg);
arr.map(func, thisArg);
thisArg is the optional last argument
The value of thisArg parameter becomes this for func.
let army = {
  minAge: 18,
  maxAge: 27,
  canJoin(user) {
    return user.age >= this.minAge && user.age < this.maxAge;
  }
};
let users = [
  {age: 16},
  {age: 20},
  {age: 23},
  {age: 30}
];
let soldiers = users.filter(army.canJoin, army);
alert(soldiers.length); // 2
alert(soldiers[0].age); // 20
alert(soldiers[1].age); // 23
Array.from(items,mapfn,thisArg);
Array.from('123', (item, index) => item * 2); // [2, 4, 6];
Array.from('123', function(item){
  console.log(this);
  return item*2;
}, {test:"valueOfThis"});
a = Array.from('2431', function(item){
  return item*this.multiply;
}, {multiply:2});
console.log(a)
// will return : [4, 8, 6, 2]
thisArgの適用
let solution=(participant,completion)=>participant.find(name=>!completion[name]--,
              completion.map(name=>completion[name]=(completion[name]|0)+1))

Arr.flatMap( function callback(currentValue[, index[, array]]){ } [, thisArg])


入る前にアリーflat()を理解すべきです.
The flat() method creates a new array with all sub-array elements concatenated
into it recursively up to the specified depth.
多次元Arrayを設計する場合、有用な組み込み関数と見なすことが容易です.
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());
// expected output: [0, 1, 2, 3, 4]
const arr2 = [0, 1, 2, [[[3, 4]]]];
console.log(arr2.flat(2));
// expected output: [0, 1, 2, [3, 4]]
配列のすべてのインデックスを返す論理を作成したいです.
let arr = [1,2,3,4,5,4,2,2,3,1,5];
let newarr = arr.map((elem,index)=>[elem,index]);
//will return [[1,0],[2,1],[3,2],[4,3],[5,4],[4,5],[2,6],[2,7],[3,8],[1,9],[5,10]];
let item = 2;
let result = newarr.filter((elem)=>elem[0]===item).map((el)=>el[1])
//will return [1,6,7];
この場合(フィルタとマッピングを同時に使用すると、コールバック関数は複雑ではなく、簡単です)
flatMapを使うととても役に立ちます.

FlatMap()に変更


let arr = [1,2,3,4,5,4,2,2,3,1,5];
let item = 2;
let result = arr.flatMap((data,index)=> data===item ? index : []);
//will return [1,6,7]