codersx-javascript-basic

Array.Reduce (P2)

Ví dụ

// Tính tổng các phần tử của mảng

var arr = [1, 2, 3, 4, 5];

var sum = arr.reduce(function (acc, cur) {
  return (acc += cur);
});

console.log(sum);

Với cách này SYNTAX chỉ cần

SYNTAX

Ví dụ 2

Tính tổng Bill của hóa đơn mua hàng sau:

var orders = [
  { item: "A", quantity: 2, price: 1 },
  { item: "B", quantity: 3, price: 2 },
  { item: "C", quantity: 4, price: 3 },
  { item: "D", quantity: 5, price: 4 },
];

// Total = ???
var total = orders.reduce(function (total, cur) {
  console.log(total, cur);
  return (total += cur.quantity * cur.price);
});

console.log(total); // fail

Array.reduce fail

Lưu ý : cách chạy này sẽ bị lỗi vì không xác định được total ban đầu là bao nhiêu để cộng vào???

Một cách khác xử lý

var orders = [
  { item: "A", quantity: 2, price: 1 },
  { item: "B", quantity: 3, price: 2 },
  { item: "C", quantity: 4, price: 3 },
  { item: "D", quantity: 5, price: 4 },
];

var total = orders.reduce(function (acc, cur) {
  if (acc == orders[0]) {
    //Kiểm tra acc nếu là phần tử 1 thì xử lý.
    acc = acc.quantity * acc.price + cur.quantity * cur.price;
  } else {
    acc += cur.quantity * cur.price;
  }
  return acc;
});

console.log(total);

Array.reduce

var orders = [
  { item: "A", quantity: 2, price: 1 },
  { item: "B", quantity: 3, price: 2 },
  { item: "C", quantity: 4, price: 3 },
  { item: "D", quantity: 5, price: 4 },
];

var total = orders.reduce(function (total, cur) {
  console.log(total, cur);
  return (total += cur.quantity * cur.price);
}, 0); // Thêm giá trị ban đầu của total là 0 để sử dụng.

console.log(total); // 40 = 2*1 + 3*2 + 4*3 + 5*4

Array.reduce

STT Result Init
1 Number 0
2 String ’’ or “”
3 Array []
4 Object {}

So sánh chạy debug ở trên:

Array.reduce Array.reduce

Ví dụ 2:

var items = ["Tom", "Bill", "Anna"];
// Use reduce to result: '<Tom><Bill><Anna>'

var newItems = items.reduce(function (acc, cur) {
  return (acc += `<${cur}>`);
}, "");

console.log(newItems);

Bài tập

Bài tập 1

// Given an array of arrays, flatten them into a single array
/**
 * Example:
 * var arrays = [
 *    ["1", "2", "3"],
 *    [true],
 *    [4, 5, 6]
 *  ];
 *
 * flatten(arrays) // ["1", "2", "3", true, 4, 5, 6];
 */
function flatten(arr) {
  return arr.reduce(function (item, arrs) {
    return item.concat(arrs);
  }, []);
}

flatten([["1", "2", "3"], [true], [4, 5, 6]]); // ["1", "2", "3", true, 4, 5, 6]

flatten([["1", "2", "3"], [true], [4, 5, false]]); // ["1", "2", "3", true, 4, 5, false]

Bài tập 2

/**
 * Count the occurrences of each element inside an array using reduce
 * @params {array}
 * @return {object}
 * Example:
 * countOccurrences(['a', 'b', 'c', 'b', 'a']) // { a: 2, b: 2, c: 1 };
}
*/
function countOccurrences(arr) {
  return arr.reduce(function (arrItems, item) {
    if (item in arrItems) {
      arrItems[item]++;
    } else {
      arrItems[item] = 1;
    }
    return arrItems;
  }, {});
}

countOccurrences(["a", "b", "c", "b", "a"]); // { a: 2, b: 2, c: 1 }
countOccurrences([1, 1, 2, 3, 2]); // { "1": 2, "2": 2, "3": 1 }
countOccurrences(["a", "b", "x", "b", "a"]); // { a: 2, b: 2, x: 1 }