[英]Filter an array by value in nested arrays
I want to return the values of array if its values contains a specific string 如果数组的值包含特定字符串,我想返回数组的值
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);
results in 结果是
FD0E35, Torch Green,FD7B33, Crusta Green
I want exactly like this 我想要这样
["#FD0E35","#FD7B33"]
Take note that the result should inside the square brackets and with qoutes. 请注意,结果应在方括号内并带有qoutes。 Only contains hex not the equivalent name and # added.
仅包含十六进制而不是等效名称,并添加#。
Any ideas? 有任何想法吗?
You could try something like this. 您可以尝试这样的事情。
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));
The .grep()
function «Finds the elements of an array which satisfy a filter function» reference .grep()
函数«查找满足过滤函数的数组的元素» 参考
In other words, in your code it returns the "sub-array" into result
. 换句话说,在您的代码中它将“子数组”返回到
result
。
Try using a simple loop like this: 尝试使用像这样的简单循环:
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));
Notice that I used JSON.strignify()
only to see the content of the color_swatches
array in console. 注意 ,我仅在控制台中使用
JSON.strignify()
来查看color_swatches
数组的内容。
You could use a map function to transform the color_swatches
array. 您可以使用map函数来转换
color_swatches
数组。 In the map function, you can pick the first item and add a #
. 在地图功能中,您可以选择第一项并添加
#
。 Before the alert, add: 在警报之前,添加:
color_swatches = $.map(color_swatches[0], function(index, color_swatch) {
return "#" + color_swatch[0];
});
You can use the JavaScript functions Array#filter
, Array#map
and String#includes
: 您可以使用JavaScript函数
Array#filter
, Array#map
和String#includes
:
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"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.