2017-05-17 7 views
0

저는 자바 스크립트를 처음 사용하고 온라인에서 찾은 몇 가지 연습을하고 있습니다. 어떤 일이 어떻게 이루어지는 지 이해하고 싶고 어떤 접근법이 다른 접근법보다 나은 이유를 정말로 알고 싶기 때문에 필자의 접근 방식이 좋지 않거나 좋은 점에 대한 몇 가지 의견에 감사드립니다.개체 배열에있는 값의 수를 계산합니다.

XML을 가지고 SAX 파서로 처리하여 "트렌드 키워드"를 얻습니다. 전반적인 결과로, 제 기능은 가장 인기있는 5 가지를 리턴해야합니다. 내 분석 자체의 결과는 모든 children 값을 빼고 새로운 배열 결과

let flattenArr = keywords.reduce((acc, cur) => acc.concat(cur.children), []); 

에 저장하는

이제
[{ 
    attributes: {} 
    //children is just one big entry, separated by ';' 
    children: ["Comey, James B;Federal Bureau of Investigation;Trump, Donald J;United States Politics and Government"] 
    IsSelfClosing: false, 
    name: 'ADX_KEYWORDS', 
    parent: null, 
    __proto__: {} 
}] 

내 생각이었다 형식 (20) 객체와 배열입니다 제가

포맷
[["Comey, James B;Federal Bureau of Investigation;Trump, Donald J;United States Politics and Government"], 
["Trump, Donald J;Comey, James B;Federal Bureau of Investigation;United States Politics and Government"]] 

단일 값을 처리하는 데에 배열 (도 20의 길이)를 얻을 I 배열 분할

01,
let mapArr = flattenArr 
    .map(arr => arr.split(';')) 
    .reduce((acc, cur) => acc.concat(cur), []); 

결과적으로 길이 115의 새로운 배열에는 모든 단일 키워드가 분리되어 있습니다. 여기서 어떻게 진행해야할지 모르겠습니다. MDN (Array.Reduce)에서 예제를 시도했지만 실제로이 객체를 처리 할 수 ​​있는지 여부를 알지 못했습니다.

//Result from MDN example, {value: quantity} 
{ 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 } 

그래서 나는 그것의 양

{ 
    key: keyword, 
    count: n 
} 

에 대한 속성, 모든 키워드에 대한 객체를 생성하는 생각을했다 및

let countKeywords = mapArrreduce((allKeywords, keyword) => { 
    if (allKeywords[0] != null && keyword in allKeywords[keyword]) { 
    allKeywords[keyword].count++ 
    } else { 
    allKeywords.push({ 
     keyword: keyword, 
     count: 1 
    }) 
    } 
    return allKeywords; 
}, []); 

으로 이러한 목표를 달성하기 위해 노력하지만, 내 코드 아무튼 't 일을하고, 심지어 이틀 후에도 여전히 작동하도록 만들려고 노력합니다.이 질문을 게시하게되었습니다. (나는 항상 stackoverflow에서 내 답변을 발견했기 때문에 다소 새로운 것입니다. 나 자신에게 질문하십시오)

+0

마지막 조각

{ 'Comey, James B': 4, 'Federal Bureau of Investigation': 4, 'Trump, Donald J': 4, 'United States Politics and Government': 4 } 
여기

프로토 타입의 내선으로 flatMap있어 ....''누락 된가? {key : count} 구조가 훨씬 쉽게 빌드/작동 할 것으로 기대합니다. 왜 당신은 mdn 예제를 사용할 수 없습니까? –

+0

첫 번째 개체에',', 변수 이름이 무엇입니까? 'cur'? 'acc' 란 무엇입니까? 또한 하나 이상의 배열 데이터 엔티티가있는 경우에도 도움이됩니다. – brandonscript

+0

'단일 값을 처리하려면 배열을 분할하십시오. '라는 내용의 코드 조각이 오류를 발생시키지 않습니까? 귀하의 질문은 꽤 명확하지 않습니다.배열을 평평하게 한 mdn 예제는 제대로 작동합니다. –

답변

-1

이렇게 할 수 있어야합니다. 많은 중첩 배열을 사용하고 있기 때문에 평면 매핑 (reduce + concat)을 두 번해야합니다. 이를 프로토 타입 방법으로 변환하여 가독성을 간소화 할 수 있습니다.

let flattenArr = [ 
    ["Comey, James B;Federal Bureau of Investigation;Trump, Donald J;United States Politics and Government"], 
    ["Trump, Donald J;Comey, James B;Federal Bureau of Investigation;United States Politics and Government"], 
    ["Trump, Donald J;Comey, James B;Federal Bureau of Investigation;United States Politics and Government"], 
    ["Trump, Donald J;Comey, James B;Federal Bureau of Investigation;United States Politics and Government"] 
] 

let mapArr = flattenArr.reduce((a, b) => a.concat(b)).map(words => words.split(";")).reduce((a, b) => a.concat(b)) 

let orderedCount = mapArr.reduce(function (acc, cur) { 
    if (typeof acc[cur] === 'undefined') { 
    acc[cur] = 1; 
    } else { 
    acc[cur] += 1; 
    } 

    return acc; 
}, {}) 

console.log(orderedCount) 

출력 :

Array.prototype.flatMap = function(lambda) { 
    return Array.prototype.concat.apply([], this.map(lambda)); 
} 

이 그 다음을 사용 :

let mapArr = flattenArr.flatMap(a => a).map(words => words.split(";")).flatMap(a => a) 
+0

늦게 대답 해 주셔서 죄송합니다. ISP 문제 ... 저는 JavaScript 초보자이므로 프로토 타입 방법의 "사용"은 정확히 무엇입니까? 물론 프로토 타입 메소드에 대해서는 읽었지만 지금까지는이 메소드의 "사용"을 이해하지 못했습니다. – Tobias

+0

기본적으로 배열에 대한 기능을 수행하고 연쇄 할 수있는 Array 클래스의 확장입니다. – brandonscript

-1
let countKeywords = mapArr.reduce((allKeywords, keyword) => {//typo <== 
var elem=allKeywords.find(el=>el.keyword===keyword);//its an array so allKeywords[keyword] wont work... 
    if (elem) { 
     elem.count++ 
    } else { 
    allKeywords.push({ 
     keyword: keyword, 
     count: 1 
    }) 
} 
return allKeywords; 
}, []); 
관련 문제