Sunny Sunny - 1 year ago 62
Javascript Question

Javascript Higher order functions: Passing a callback function into filter not working

I'm trying to filter out an array's values by those that return true. I have a function called noRepeat which returns true if the given year has no digits repeated, and false otherwise.

I have another function called no_repeats(yearStart, yearEnd) that creates an array of years from start to end. I want to filter out this array by those years that have no digits repeated and I'm not sure why that isn't working. Any ideas? I've included the problem statement as well and in the code I show what my output is versus what it should be.

Write a function, `no_repeats(year_start, year_end)`, which takes a
range of years and outputs those years which do not have any
repeated digits.

You should probably write a helper function, `no_repeat?(year)` which
returns true/false if a single year doesn't have a repeat.

Difficulty: 1/5

function no_repeats(yearStart, yearEnd){
//call no repeats on each year from yearStart to yearEnd and return an array of years that have noRepeat(year) === true
var yearRangeArr = [];
var returnArr = [];
while (yearEnd >= yearStart){
return noRepeat(year);
return yearRangeArr;


function noRepeat(year){ //works
//create an array pushing each year's digits
// if arr.indexOf(digit) > -1 then the digit already exists, so return false
// else append the digit, and if no digit repeats, return true
year = year.toString();
var repeatArr = [];
for (i = 0; i < year.length; i++){
if (repeatArr.indexOf(year[i]) > -1){ //if the digit exists in arr
return false;
return true;

//var testArr= [1,2,3,4,2];

console.log(no_repeats(1234, 1234)); //== [1234]);
console.log(no_repeats(1123, 1123)); // == []); ANSWER SHOULD BE [], I'M GETTING [1123].

Answer Source

filter() returns new value, it does not mutate the original object. You have to assign returned value to your variable:

yearRangeArr = yearRangeArr.filter(function(year){
    return noRepeat(year);