首页 > 解决方案 > Javascript 检查项目在列表中出现的次数,然后将列表添加在一起

问题描述

我试图检查一个固定装置有多少次发布关于它的帖子,我有一个所有团队的列表,然后是所有有固定装置的团队。这是固定装置的列表。

(8) [Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1)]
0: ["Fulham v Arsenal"]
1: ["Crystal Palace v Southampton"]
2: ["Liverpool v Leeds United"]
3: ["West Ham United v Newcastle United"]
4: ["West Bromwich Albion v Leicester City"]
5: ["Tottenham v Everton"]
6: ["Sheffield United v Wolverhampton Wanderers"]
7: ["Brighton and Hove Albion v Chelsea"]

然后是关于他们的帖子

0: ["Liverpool v Leeds United"]
1: ["Crystal Palace v Southampton"]
2: ["Crystal Palace v Southampton"]

所以我基本上想制作一个像这样的最终数组:

 (8) [Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1)]
0: ["Fulham v Arsenal", 0]
1: ["Crystal Palace v Southampton", 2]
2: ["Liverpool v Leeds United", 1]
3: ["West Ham United v Newcastle United", 0]
4: ["West Bromwich Albion v Leicester City", 0]
5: ["Tottenham v Everton", 0]
6: ["Sheffield United v Wolverhampton Wanderers", 0]
7: ["Brighton and Hove Albion v Chelsea", 0]

我正在使用此代码制作谷歌条形图。这是我到目前为止创建的代码。

    var fixposts = [];
var posts = [];
var postsc = [];
var finala = [];
var y = 0;
var z = 0;

function getOccurrence(array, value) {
    var count = 0;
    array.forEach((v) => (v === value && count++));
    return count;
}
<c:forEach items="${fixtures}" var="fix" varStatus="count"> 
fixposts.push(['<c:out value="${fix.home.teamName} v ${fix.away.teamName}"/>']);
</c:forEach>
console.log(fixposts);
<c:forEach items="${posts}" var="post" varStatus="count"> 
posts.push(['<c:out value="${post.fixture.home.teamName} v ${post.fixture.away.teamName}"/>']);
</c:forEach>

console.log(posts);

fixposts 数组是当周有固定装置的所有团队,而帖子是当周有固定装置的团队以及关于它们的帖子。然后我将如何将这两者结合起来,这样我就可以拥有一个包含所有灯具的数组,以及关于它们的 0 或多少帖子?谢谢你。

标签: javascriptarraysjsp

解决方案


您可以使用for-loop迭代您的fixposts&posts然后检查值是否匹配,如果是,则增加count值并存储在新数组中。

演示代码

//this you will get from jsp code ..
var fixposts = [
  ["Fulham v Arsenal"],
  ["Crystal Palace v Southampton"],
  ["Liverpool v Leeds United"],
  ["West Ham United v Newcastle United"],
  ["West Bromwich Albion v Leicester City"],
  ["Tottenham v Everton"],
  ["Sheffield United v Wolverhampton Wanderers"],
  ["Brighton and Hove Albion v Chelsea"]
]

var posts = [
  ["Liverpool v Leeds United"],
  ["Crystal Palace v Southampton"],
  ["Crystal Palace v Southampton"]
]
var new_array = [];
//loop through fixpost array
for (var i = 0; i < fixposts.length; i++) {
  var count = 0;
  //use `0` because fixpost is array of arary so inner array is `0` index
  for (var j = 0; j < posts.length; j++) {
    //comapre
    if (fixposts[i][0] == posts[j][0]) {
      count++;
    }
  }
  //store in new array
  new_array.push([fixposts[i][0], count])
}

console.log(new_array)


推荐阅读