Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* REDUCE METHOD */
- //reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }, initialValue)
- /*
- const array1 = [1, 2, 3, 4];
- // 0 + 1 + 2 + 3 + 4
- const initialValue = 0;
- const sumWithInitial = array1.reduce(
- (accumulator, currentValue) => accumulator + currentValue,
- initialValue
- );
- console.log(sumWithInitial);
- // expected output: 10
- */
- /*
- Why is important to declare initValue?
- !!!
- The first time that the callback is run there is no
- "return value of the previous calculation".
- If supplied, an initial value may be used in its place.
- Otherwise the array element at index 0 is used as
- the initial value and iteration starts
- from the next element (index 1 instead of index 0).
- */
- //example without init value
- // average calc in array with reduce
- let result = [1, 2, 3].reduce((acc, x, index, arr) => (
- acc + x / arr.length
- ));
- console.log(result); // --> 2,6,
- //corret avg value should be 1+2+3=6/3=2 or 1/3+2/3+3/3=2
- //but the first zero-indexed element is used as initValue
- // operation start applying from the 1-indexed element
- console.log(1 + 2 / 3 + 3 / 3); // --> 2,6
- // with init value 0, correct way:
- // 0+1/3+2/3+3/3=2
- let resultOk = [1, 2, 3].reduce((acc, x, index, arr) => (
- acc + x / arr.length
- ), 0);
- console.log(resultOk); //--> 2
- //-------------------------------
- //01 Returning Array:
- // filter even with reduce:
- let numbers = [20, 10, 5, 6, 7];
- console.log(numbers.reduce((acc, el) => {
- if (el % 2 == 0) {
- acc.push(el);
- }
- return acc;
- }, []))
- //---------------------------------------
- //02 return objet:
- let n = 100;
- let resObj = ['keyA', 'keyZ', 'key0', 'code00', 345].reduce((acc, curEl, ind, arr) => {
- n++;
- acc[curEl] = n;
- return acc;
- }, {'000':'xxx'});
- console.log(resObj); //--> {345: 105, 000: 'xxx', keyA: 101, keyZ: 102, key0: 103, code00: 104}
- //----- - -- -------------------------
- //03 return string, {length} is instead of Array.length
- let resStr = ['how', 'to', 'use', 'reduce', 'method', '!'].reduce((acc, x, index, { length }) => {
- let space = ' ';
- if (index == length -1) {
- space='';
- }
- acc += space+x;
- return acc;
- }, 'Teach');
- console.log(resStr);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement