簡體   English   中英

如何計算JavaAcript數組中元素的出現次數

[英]How to count the number of occurances of an element in JavaAcript array

如何計算javascript數組htdata中一個特定元素的出現次數

我的一些代碼

htmldata.forEach(function(htdata){
    htdata['field_name'] == 'heading';
    var char = htdata['field_name'] == 'heading';
    if(char.length > 1)
    {
        alert("hiii");
    }
}

給定注釋中的新信息,這里是您的完整解決方案。 請注意,在帶說明的長格式解決方案之后,我將“生產”版本放在最后。

// The problem:
// Find the number of elements with field_name === "heading" in the
// following object:
const htdata =  {
    0:{id:"199",field_name:"heading"},
    1:{id:"200",field_name:"textbox"},
    2: {id:"201",field_name:"heading"}
}


// The long form solution with explanation:

// convert the original data object into an array so that we can
// use the built in javascript array manipulation functions like:
// reduce, map, and filter.
// 
// see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
const haystack = Object.values(htdata)

/*    haystack now looks like this:
    [
        { id: "199", field_name: "heading" },
        { id: "200", field_name: "textbox" },
        { id: "201", field_name: "heading" },
    ]
*/

// now, we can filter haystack into a new array that only includes
// elements with the field_name === "heading":
const filteredHaystack = haystack.filter(i => i.field_name === "heading")

/*  filteredHaystack now looks like this:
    [ 
        { id: '199', field_name: 'heading' },
        { id: '201', field_name: 'heading' }, 
    ]
*/

// now, we simply count the elements in filteredHaystack to get the
// number of elements with field_name === "heading" in the original data:

const headingsCount = filteredHaystack.length

console.log(headingsCount)  // 2


// The more elegant version of the solution:
const count = Object.values(htdata)
    .filter(i => i.field_name === "heading")
    .length

console.log(count) // 2

這是計算數組中不同值的出現的示例。

var a = ["toto","tata","toto","foo","foo","bar","foo","toto","tata","toto"];
var countPerValue = {};
a.map(function(i) {
  if (!countPerValue[i]) countPerValue[i] = 0; // init counter to 0 for this value
  countPerValue[i]++;
});
console.log(countPerValue); // {toto: 4, tata: 2, foo: 3, bar: 1}
console.log(countPerValue["foo"]); // 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM