如果数组中的字符串与另一个数组中的字符串匹配,如何推送到新数组?

时间:2017-07-31 17:02:31

标签: javascript jquery

我有两个数组:

var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var words = ["27","-","28","August","663","CE"];

字符串August存在于两者中,我需要将August推送到新的多维数组:

dates.push({
    Day : [], 
    Month : [],
    Year : [],
    Prefix : []
});
dates[0].Time.push(d);

这是我创建第二个数组的方法,因此我们可以使用一个循环,但我不确定如何检查字符串是否在另一个数组中,如果是,则将其推送到新数组。 / p>

var string = "27 - 28 August 663 CE";
var words = string.split(" ");
for (var i = 0; i < words.length - 1; i++) {
    words[i] += " ";
    // here we check matches and push
}
var array = words;

3 个答案:

答案 0 :(得分:4)

我会在几个月内使用Set,以避免你必须循环它,但可以在恒定时间内知道你是否有匹配值:

var months = new Set(["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]);
var words = ["27","-","28","August","663","CE"];

const d = {
    days : [], 
    months : [],
    years : [],
    suffixes : []
}
for (const word of words) {
    if (months.has(word)) {
        d.months.push(word);
    } else if (+word < 32) {
        d.days.push(+word);
    } else if (+word < 2200) {
        d.years.push(+word);
    } else if (/\w+/.test(word)) {
        d.suffixes.push(word);
    }
}

console.log(d);
.as-console-wrapper { max-height: 100% !important; top: 0; }

注意:对你的属性使用复数,因此很明显它们是数组,并且不要用资本启动它们,因为它通常是为类/构造函数保留的。此外,前缀是之前的东西。你想要后缀。

答案 1 :(得分:0)

只需按照特定条件过滤单词(例如,如果它们包含在月份数组中):

dates.push({
  Day :  words.filter(word=>parseInt(word)&&word.length === 2),
  Month : words.filter(word=>months.includes(word)),
  Year : words.filter(word=>parseInt(word)&&word.length === 4),
  Prefix : ["i dont know what tnis is"]
});

答案 2 :(得分:0)

您可以使用对象并检查小写字词。

var months = { january: true, february: true, march: true, april: true, may: true, june: true, july: true, august: true, september: true, october: true, november: true, december: true },
    words = ["27", "-", "28", "August", "663", "CE"],
    result = [];
    
words.forEach(function (w) {
    months[w.toLowerCase()] && result.push(w);
});

console.log(result);