var arr = [1,9,9,0,1,2,3,4,1,2,3,4,2,6,9,9]; var f = (ar, b, l) => (ar = ar.filter(a => a === b), l ? ar.length : ar.join('')) alert(f(arr, 2, true)); alert(f(arr, 2)); alert(f(arr, 9));