>  기사  >  웹 프론트엔드  >  예제를 통해 JS Reduce() 메서드를 사용하는 5가지 방법 알아보기

예제를 통해 JS Reduce() 메서드를 사용하는 5가지 방법 알아보기

青灯夜游
青灯夜游앞으로
2021-01-27 19:16:422034검색

예제를 통해 JS Reduce() 메서드를 사용하는 5가지 방법 알아보기

reduce() 메서드는 배열의 각 요소에 대해 (귀하가 제공한) 감속기 함수를 실행하여 단일 출력 값을 생성합니다.

reduce() 메서드는 배열의 모든 요소를 ​​숫자, 객체 또는 문자열일 수 있는 단일 출력 값으로 줄입니다. reduce() 메서드에는 두 개의 매개변수가 있습니다. 첫 번째는 reduce() 方法将一个数组中的所有元素还原成一个单一的输出值,输出值可以是数字、对象或字符串。 reduce() 方法有两个参数,第一个是回调函数,第二个是初始值

回调函数

回调函数在数组的每个元素上执行。回调函数的返回值是累加结果,并作为下一次调用回调函数的参数提供。回调函数带有四个参数。

  • Accumulator(累加器)——累加器累加回调函数的返回值。
  • Current Value(当前值)——处理数组的当前元素。
  • Current Index(当前索引)——处理数组当前元素的索引。
  • Source Array(源数组)

Current Index Source Array 是可选的。

初始值

如果指定了初始值,则将累加器设置为 initialValue 作为初始元素。否则,将累加器设置为数组的第一个元素作为初始元素。

arr.reduce(callback(accumulator, currentValue[,index[,array]])[, initialValue])

在下面的代码片段中,第一个累加器(accumulator)被分配了初始值0。currentValue 是正在处理的 numbersArr 数组的元素。在这里,currentValue 被添加到累加器,在下次调用回调函数时,会将返回值作为参数提供。

const numbersArr = [67, 90, 100, 37, 60];
 
const total = numbersArr.reduce(function(accumulator, currentValue){
    console.log("accumulator is " + accumulator + " current value is " + currentValue);
    return accumulator + currentValue;
}, 0);
 
console.log("total : "+ total);

输出

accumulator is 0 current value is 67
accumulator is 67 current value is 90
accumulator is 157 current value is 100
accumulator is 257 current value is 37
accumulator is 294 current value is 60
total : 354

JavaScript reduce用例

1.对数组的所有值求和

在下面的代码中,studentResult 数组具有5个数字。使用 reduce() 方法,将数组减少为单个值,该值将 studentResult 数组的所有值和结果分配给 total

const studentResult = [67, 90, 100, 37, 60];
 
const total = studentResult.reduce((accumulator, currentValue) => accumulator +currentValue, 0);
 
console.log(total); // 354

2.对象数组中的数值之和

通常,我们从后端获取数据作为对象数组,因此,reduce() 方法有助于管理我们的前端逻辑。在下面的代码中,studentResult 对象数组有三个科目,这里,currentValue.marks 取了 studentResult 对象数组中每个科目的分数。

const studentResult = [
  { subject: '数学', marks: 78 },
  { subject: '物理', marks: 80 },
  { subject: '化学', marks: 93 }
];
 
const total = studentResult.reduce((accumulator, currentValue) => accumulator + currentValue.marks, 0);
 
console.log(total); // 251

3.展平数组

“展平数组”是指将多维数组转换为一维。在下面的代码中,twoDArr 2维数组被转换为 oneDArr 一维数组。此处,第一个 [1,2] 数组分配给累加器 accumulator,然后 twoDArr 数组的其余每个元素都连接到累加器。

const twoDArr = [ [1,2], [3,4], [5,6], [7,8] , [9,10] ];
 
const oneDArr = twoDArr.reduce((accumulator, currentValue) => accumulator.concat(currentValue));
 
console.log(oneDArr);
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

4.按属性分组对象

根据对象的属性,我们可以使用 reduce() 方法将对象数组分为几组。通过下面的代码片段,你可以清楚地理解这个概念。这里,result 对象数组有五个对象,每个对象都有 subjectmarks 属性。如果分数大于或等于50,则该主题通过,否则,主题失败。

reduce() 用于将结果分组为通过和失败。首先,将 initialValue 分配给累加器,然后 push() 方法在检查条件之后将当前对象添加到 passfail 属性中作为对象数组。

const result = [
  {subject: '物理', marks: 41},
  {subject: '化学', marks: 59},
  {subject: '高等数学', marks: 36},
  {subject: '应用数学', marks: 90},
  {subject: '英语', marks: 64},
];
 
let initialValue = {
  pass: [], 
  fail: []
}
 
const groupedResult = result.reduce((accumulator, current) => {
  (current.marks >= 50) ? accumulator.pass.push(current) : accumulator.fail.push(current);
  return accumulator;
}, initialValue);
 
console.log(groupedResult);

输出

{
 pass: [
  { subject: ‘化学’, marks: 59 },
  { subject: ‘应用数学’, marks: 90 },
  { subject: ‘英语’, marks: 64 }
 ],
 fail: [
  { subject: ‘物理’, marks: 41 },
  { subject: ‘高等数学’, marks: 36 }
 ]
}

5.删除数组中的重复项

在下面的代码片段中,删除了 plicatedArr 数组中的重复项。首先,将一个空数组分配给累加器作为初始值。accumulator.includes() 检查 duplicatedArr 数组的每个元素是否已经在累加器中可用。如果 currentValue 在累加器中不可用,则使用 push() 将其添加。

const duplicatedsArr = [1, 5, 6, 5, 7, 1, 6, 8, 9, 7];
 
const removeDuplicatedArr = duplicatedsArr.reduce((accumulator, currentValue) => {
  if(!accumulator.includes(currentValue)){
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);
 
console.log(removeDuplicatedArr);
// [ 1, 5, 6, 7, 8, 9 ]

总结

在本文中,我们讨论了数组 reduce() 方法。首先介绍 reduce() 方法,然后,使用一个简单的示例讨论其行为。最后,通过示例讨论了 reduce()콜백 함수

이고 두 번째는
초기값

입니다.

콜백 함수

콜백 함수는 배열의 각 요소에서 실행됩니다. 콜백 함수의 반환 값은 누적된 결과이며, 다음 콜백 함수 호출을 위한 매개 변수로 제공됩니다. 콜백 함수는 4개의 매개변수를 사용합니다.

Accumulator

(누산기) - 누산기는 콜백 함수의 반환 값을 누적합니다.

  • Current Value(현재 값) - 배열의 현재 요소를 처리합니다.
  • Current Index🎜(현재 인덱스) - 배열의 현재 요소 인덱스를 처리합니다.
  • 🎜소스 배열🎜(소스 배열)
  • 🎜현재 인덱스 소스 배열 은 선택 사항입니다. 🎜

    초기값

    🎜초기값이 지정되면 누산기를 초기 요소로 initialValue로 설정합니다. 그렇지 않으면 누산기를 배열의 첫 번째 요소로 초기 요소로 설정합니다. 🎜rrreee🎜아래 코드 조각에서 첫 번째 누산기(accumulator)에는 초기 값 0이 할당됩니다. currentValue는 처리 중인 numbersArr 배열의 요소입니다. 여기서는 누산기에 currentValue가 추가되고 다음에 콜백 함수가 호출될 때 반환값이 매개변수로 제공됩니다. 🎜rrreee🎜Output🎜rrreee

    JavaScript 사용 사례 줄이기

    1. 배열의 모든 값 합계

    🎜아래 코드에서 studentResult 배열에는 5개의 숫자가 있습니다. reduce() 메서드를 사용하여 studentResult 배열의 모든 값과 결과를 total에 할당하는 단일 값으로 배열을 줄입니다. 🎜rrreee

    2. 객체 배열에 있는 값의 합

    🎜보통 우리는 백엔드에서 객체 배열로 데이터를 가져옵니다. 따라서 reduce() code> 메소드는 프런트 엔드 로직을 관리하는 데 도움이 됩니다. 다음 코드에서 <code>studentResult 개체 배열에는 세 개의 주제가 있습니다. 여기서 currentValue.marksstudentResult 개체 배열에서 각 주제의 표시를 가져옵니다. . 🎜rrreee

    3. 배열 평면화

    🎜"평면 배열"은 다차원 배열을 1차원으로 변환하는 것을 말합니다. 다음 코드에서는 twoDArr 2D 배열이 oneDArr 1D 배열로 변환됩니다. 여기서 첫 번째 [1,2] 배열은 누산기 accumulator에 할당되고 twoDArr 배열의 나머지 각 요소는 다음과 연결됩니다. 누산기. 🎜rrreee

    4. 속성별로 개체 그룹화

    🎜 개체의 속성에 따라 reduce() 메서드를 사용하여 나눌 수 있습니다. 객체 배열을 여러 그룹으로 나눕니다. 다음 코드 조각을 통해 이 개념을 명확하게 이해할 수 있습니다. 여기서 result 개체 배열에는 각각 subjectmarks 속성이 있는 5개의 개체가 있습니다. 점수가 50보다 크거나 같으면 주제가 통과되고, 그렇지 않으면 해당 주제가 실패합니다. 🎜🎜reduce()는 결과를 합격과 실패로 그룹화하는 데 사용됩니다. 먼저 initialValue가 누산기에 할당된 다음 push() 메서드는 현재 객체를 passfail에 추가합니다. 조건 속성을 ​​객체 배열로 사용합니다. 🎜rrreee🎜Output🎜rrreee

    5. 배열에서 중복 제거

    🎜아래 코드 조각에서는 plicatedArr가 중복 배열에서 제거됩니다. . 먼저, 빈 배열이 누산기에 초기 값으로 할당됩니다. accumulator.includes()duplicatedArr 배열의 각 요소가 이미 누산기에서 사용 가능한지 여부를 확인합니다. currentValue를 누산기에서 사용할 수 없는 경우 push()를 사용하여 추가하세요. 🎜rrreee

    요약

    🎜이 기사에서는 배열 reduce() 메서드에 대해 논의했습니다. reduce() 메서드를 먼저 소개한 다음 간단한 예를 사용하여 해당 동작을 설명합니다. 마지막으로 reduce() 메서드의 가장 일반적인 5가지 사용 사례를 예제와 함께 설명합니다. JavaScript 초보자라면 이 글이 도움이 될 것입니다. 🎜🎜🎜영어 원본 주소: https://medium.com/javascript-in-plain-english/5-use-cases-for-reduce-in-javascript-61ed243b8fef🎜🎜저자: wathsala danthasinghe🎜🎜🎜더 많은 프로그래밍을 위해 관련 지식이 있으면 🎜프로그래밍 비디오🎜를 방문하세요! ! 🎜

    위 내용은 예제를 통해 JS Reduce() 메서드를 사용하는 5가지 방법 알아보기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

    성명:
    이 기사는 segmentfault.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제