将数组推送到一个数组,然后循环遍历新数组

时间:2018-01-31 20:40:00

标签: javascript arrays loops frequency

我需要遍历几个数组,以找出特定值出现的频率。

我可以将值传递给一个新数组,这样可行,但是当我尝试遍历它时,它似乎不起作用。

由于这是针对类的,我不能使用jQuery - 仅仅是逻辑!!

var mon = ["Ez, Caro"];
var tue = ["Ez, Matt, Pablo"];
var wed = ["Marta"];
var thur = ["Ez, Matt"];
var freq = 0;
var arr = [];

var input = prompt ("Search a name");

arr.push(mon, tue, wed, thur);

for (var i = 0; i<arr.length; i++){
  if (arr[i] == input){

    freq = freq + 1;
  }

}
document.write("It appears " + freq + " time(s)")

8 个答案:

答案 0 :(得分:1)

问题是,使用Array.push创建一个数组数组而不是合并它们,这是所需的结果。查看Array.concat,或尝试使用ES6 spread语法。

答案 1 :(得分:1)

假设每个数组应该有多个字符串而不是问题中的一个,你可以使用vanilla JavaScript执行类似下面的操作。检查注释的逻辑。

&#13;
&#13;
var mon = ["Ez", "Caro"];
var tue = ["Ez", "Matt", "Pablo"];
var wed = ["Marta"];
var thur = ["Ez", "Matt"];

//combine your arrays for simplicity
var arr = mon.concat(tue).concat(wed).concat(thur);

//use an object as a map to keep track of count
var map = {};
for (let i = 0; i < arr.length; i++) {
  if (!map[arr[i]]) {
    map[arr[i]] = 1;
  } else {
    map[arr[i]] = map[arr[i]] + 1;
  }
}

//get the user input
var input = prompt("Search a name");

//store the count of requested input (case-sensitive)
var countOfRequested = map[input] ? map[input] : 0;

//display to the user
console.log(input + ' appears ' + countOfRequested + ' times.');
&#13;
&#13;
&#13;

答案 2 :(得分:1)

您可以将数组的所有成员合并为一个数组,并使用.reduce来总结您定位的输入。

要合并这些值,您可以使用ES2015 spread syntax

var combinedArray = [...mon, ...tue, ...wed, ...thur];

带有.concat的旧版javascript(我使用apply to not mutate the array):

var combinedArray = [].concat.apply([],[mon,tue,wed,thur]);

这是一个正在运行的例子:

var mon = ["Ez", "Caro"];
var tue = ["Ez", "Matt", "Pablo"];
var wed = ["Marta"];
var thur = ["Ez", "Matt"];
// ES6
var combinedArray = [...mon, ...tue, ...wed, ...thur];
// ES5
//var combinedArray = [].concat.apply([],[mon,tue,wed,thur]);

function countInput(input, arr) {
  var count = arr.reduce(function(sum, current) {
    if (current === input) {
      sum += 1;
    }
    return sum;
  }, 0);
  return count;
}

var input = 'Ez';
var count = countInput(input, combinedArray);
console.log("The count of " + input + ' - ',count);

答案 3 :(得分:0)

关闭,但不完全。 Push将整个元素插入到数组中。这包括一周中的每一天都是阵列的事实。

arr = [["Ez, Caro"], ["Ez, Matt, Pablo"], ["Marta"], ["Ez, Matt"]]

您正在寻找concat,或者在数组中选择字符串本身,方法是抓取元素的索引号,即0

arr.push(mon[0], tue[0], wed[0], thur[0]);

arr.concat(mon, tue, wed, thur)

作为旁注,您不必将其写为freq = freq + 1;freq += 1是每个人都使用的惯例。

答案 4 :(得分:0)

通过使用push函数,你可以创建数组数组..所以你可以使用嵌套循环迭代这个2d数组..所以你的代码将是

        var mon = ["Ez", "Caro"];
        var tue = ["Ez", "Matt", "Pablo"];
        var wed = ["Marta"];
        var thur = ["Ez", "Matt"];
        var freq = 0;
        var arr = [];
        var input = prompt ("Search a name");
        arr.push(mon, tue, wed, thur);
        for (i = 0; i<arr.length; i++)
            for(j = 0; j < arr.length; j++)
                if (arr[i][j] == input)
                    freq++;
        document.write("It appears " + freq + " time(s)")

答案 5 :(得分:0)

以下代码应该有效。它写的是ES6,如果你对此不满意,请告诉我。

const mon = ["Ez", "Caro"];
const tue = ["Ez", "Matt", "Pablo"];
const wed = ["Marta"];
const thur = ["Ez", "Matt"];

const names = [...mon, ...tue, ...wed, ...thur]

const input = prompt ("Search a name");

const freq = names.filter(a => a===input).length

document.write("It appears " + freq + " time(s)")

答案 6 :(得分:0)

首先要看的是你的数组。因为你的引号在哪里,我认为你没有得到预期的价值。例如,在for($i = new DateTime($ClinicStartDate); $i <= $EndDate; $i->modify($SchCount)){ $Output[$ArrayCount]['PlanID'] = $Clinic->PlanID; $Output[$ArrayCount]['id'] = $Clinic->id; $Output[$ArrayCount]['ClinicCode'] = $Clinic->ClinicCode; $Output[$ArrayCount]['SchDay'] = $Clinic->SchDay; $Output[$ArrayCount]['SchWeek'] = $Clinic->SchWeek; $Output[$ArrayCount]['SchWeekBetween'] = $Clinic->SchWeekBetween; $Output[$ArrayCount]['Date'] = new DateTime($i->format("Y-m-d")); $ArrayCount++; } 我相信你期待2个值:“Ez”和“Caro”,但是,缺少的引号意味着你在数组中只有一个元素:“Ez,Caro”。改为将数组改为:

mon

然后,您可以像这样创建var mon = ["Ez", "Caro"]; var tue = ["Ez", "Matt", "Pablo"]; var wed = ["Marta"]; var thur = ["Ez", "Matt"]; var freq = 0;

arr

这需要一个空数组(var arr = [].concat(mon, tue, wed, thur); )并合并你正在查看的4个数组。从这里开始,循环应该可以正常工作。所以,整件事:

[]

答案 7 :(得分:0)

可以使用嵌套循环:

 const days = [mon, tue, wed, thur];

 let freq = 0, input = "Ez";

 for(const day of days){
    for(const person of day){
        if(person === input) freq++;
    }
 }