Reputation: 1724
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. Only contains hex not the equivalent name and # added.
Any ideas?
Upvotes: 0
Views: 100
Reputation: 21854
You can use the JavaScript functions Array#filter
, Array#map
and 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"]
Upvotes: 0
Reputation: 977
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));
Upvotes: 2
Reputation: 33933
The .grep()
function «Finds the elements of an array which satisfy a filter function» reference
In other words, in your code it returns the "sub-array" into 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.
Upvotes: 1
Reputation: 441
You could use a map function to transform the color_swatches
array. 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];
});
Upvotes: 0