1

I have this code below with 3 arrays and sometime the green array will be completely empty how do i make it so that when i combine all my arrays and loop through my foreach it doesn't print undefined value? Any help would be greatly appreciated.

var blue = job['blue-color'];
var red = job['red-color'];
var green = job['green-color']; 
var colors = blue .concat(red,green);


var colorbooks = '<div">';
$.each(colors, function (index) {
  colorbooks += '<div">' + colors[index] + '</div>';
});
colorbooks+= '</div>';
1
  • can you show job ? Commented Jun 27, 2018 at 7:31

3 Answers 3

2

You could just check if your value is truthy before printing it :

var blue = job['blue-color'] || [];
var red = job['red-color'] || [];
var green = job['green-color'] || [];
var colors = blue.concat(red, green);


var colorbooks = '<div">';
$.each(colors, function(index) {
                            //If it's undefined, it will print an empty String instead
  colorbooks += '<div">' + (colors[index] || '') + '</div>';
});
colorbooks += '</div>';

As @Margon advised in the comments, if job['XXX-color'] is undefined, you can also assign an empty array to your variable instead : var blue = job['blue-color'] || [];

Sign up to request clarification or add additional context in comments.

3 Comments

May I suggest to also check also "job['X-color']" is different from undefined? Like you did in your (colors[index] || '') So it become (job['green-color'] || []) and so on..
@Zenoo is there no way to make it print nothing instead?
@Bobby That's exactly what that does.
0

You can first use filter() to get the defined values only and then use forEach() to console.log all those values:

var blue = [''];
var red = ['red1'];
var green = ['', 'blue1']
var colors = blue .concat(red,green);
console.log(colors);
colors.filter(item => item).forEach(x => console.log(x));

Comments

0

This might help

<script>

var a = [''];
var b= ['red1'];
var v = ['', 'blue1']
var colors = v .concat(a,b);
$.each(colors,function(index,value){
alert(value);
});

</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.