在嵌套数组中按值过滤数组

时间:2016-12-16 06:43:40

标签: javascript jquery arrays

如果数组的值包含特定的字符串

,我想返回数组的值
var names=  [
    ["FCFEDA", "Moon Glow"],
    ["FCFFE7", "China Ivory"],
    ["FCFFF9", "Ceramic"],
    ["FD0E35", "Torch Green"],
    ["FD5B78", "Wild Watermelon"],
    ["FD7B33", "Crusta Green"]

];
var color_swatches = [];
var result = $.grep(names, function(v,i) {
    if(v[1].indexOf("Green") > -1){
        return v[0];
    }
})
color_swatches.push(result);
alert(color_swatches);

结果

    FD0E35, Torch Green,FD7B33, Crusta Green

我想要完全像这样

    ["#FD0E35","#FD7B33"]

请注意,结果应位于方括号内并带有qoutes。仅包含十六进制而不是等效名称和#Added。

有什么想法吗?

4 个答案:

答案 0 :(得分:2)

你可以尝试这样的事情。

var names=  [
    ["FCFEDA", "Moon Glow"],
    ["FCFFE7", "China Ivory"],
    ["FCFFF9", "Ceramic"],
    ["FD0E35", "Torch Green"],
    ["FD5B78", "Wild Watermelon"],
    ["FD7B33", "Crusta Green"]

];
var color_swatches = [];
names.forEach(item => {
	if(item[1].indexOf("Green") > -1){
        color_swatches.push('#' + item[0]);
    }
});
console.log(color_swatches);
console.log(JSON.stringify(color_swatches));

答案 1 :(得分:1)

doc_install expressjs 函数«查找满足过滤函数的数组元素»reference

换句话说,在您的代码中,它将“子数组”返回到.grep()

尝试使用这样的简单循环:

result

注意我只使用 var names= [ ["FCFEDA", "Moon Glow"], ["FCFFE7", "China Ivory"], ["FCFFF9", "Ceramic"], ["FD0E35", "Torch Green"], ["FD5B78", "Wild Watermelon"], ["FD7B33", "Crusta Green"] ]; var color_swatches = []; for(i=0;i<names.length;i++){ if(names[i][1].indexOf("Green") > -1){ color_swatches.push( names[i][0] ); } } //color_swatches.push(result); console.log(JSON.stringify(color_swatches));来查看控制台中JSON.strignify()数组的内容。

答案 2 :(得分:0)

您可以使用map函数转换color_swatches数组。在地图功能中,您可以选择第一个项目并添加#。在提醒之前,请添加:

color_swatches = $.map(color_swatches[0], function(index, color_swatch) {
    return "#" + color_swatch[0];
});

答案 3 :(得分:0)

您可以使用JavaScript函数Array#filterArray#mapString#includes

&#13;
&#13;
var names = [
  ["FCFEDA", "Moon Glow"],
  ["FCFFE7", "China Ivory"],
  ["FCFFF9", "Ceramic"],
  ["FD0E35", "Torch Green"],
  ["FD5B78", "Wild Watermelon"],
  ["FD7B33", "Crusta Green"]
]

console.log(names.filter(n => n[1].includes('Green')).map(n => `#${n[0]}`))

// ["#FD0E35","#FD7B33"]
&#13;
&#13;
&#13;