0

I am trying to write a function that takes in an array and a max cutoff number. The number is the max number that the string can contain, and this number replaces all array elements greater than the number. For example, if the array is [1,2,3,4,5,6] and the cutoff number is 4, the output should be [1,2,3,4,4,4].

This is what I have so far, but I am only getting [1,2,3,4,5] as the output instead of [1,2,3,3,3]. Any suggestions??

var maxCutoff = function(array, number) {
    for (var i=0; i<array.length; i++) {
        if (array.indexOf(i) > number) {
            array.pop();
            array.push(number);
            return array;
        } else if (array.indexOf(i) <= number) {
            return array;
        }
    }
}
console.log(maxCutoff([1,2,3,4,5], 3));

3 Answers 3

3

You can deal with it with a simple one-liner, using Array#map.

const maxCutoff = (arr, num) => arr.map(v => v > num ? num : v);

console.log(maxCutoff([1,2,3,4,5], 3));

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

Comments

2

You could use a ternary for the result for mapping.

const maxCutoff = (array, value) => array.map(a => a > value ? value : a);

console.log(maxCutoff([1, 2, 3, 4, 5], 4));

or Math.min for the result for mapping.

const maxCutoff = (array, value) => array.map(a => Math.min(a, value));

console.log(maxCutoff([1, 2, 3, 4, 5], 4));

1 Comment

Math.min(a, value)?
0

The solution is quite simple, you just need to change the element to max. Assuming you are a beginner to JS, the below solution should be more comprehendable to you. Another answer that uses map, might come off as magical, that should be more efficient, but it depends on how well the browser handles the map function, for most cases, browsers do implement it quite fine

var maxCutoff = function(array, number) {
    for (var i=0; i<array.length; i++) {
        if(array[i]>number)
          array[i] = number;
    }
    return array
}
console.log(maxCutoff([1,2,3,4,5], 3));

1 Comment

thank you!! this makes a lot of sense, and yes i am just beginning to learn JS

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.