1

i was wondering if there is a way to get an array with minimum and maximum values get by another array, or something like this:

var numbers = ['10','15','20','25','30','35','40','45','50'];  

var getnumbers = function(min,max){
 //return a result that is push to another array, in this case "results"
};
getnumbers(10,30);
console.log(results);

the output should give me something like 10 - 15 - 20 - 25 - 30

3
  • You can define a global array like numbers and push in it, or you can create a temp array in getnumbers and return it. Commented Nov 18, 2015 at 14:08
  • ok, get it, but i'm not sure how to get the numbers array value like the output. Commented Nov 18, 2015 at 14:11
  • I believe @Nina, answer is perfect, but an alternative could be looping over numbers array and pushing it into an array and return it. Commented Nov 18, 2015 at 14:43

4 Answers 4

3

A slightly different approach, with a customized callback function for filtering.

function filterNumbers(min, max) {
    return function (a) { return a >= min && a <= max; };
}

var numbers = ['10', '15', '20', '25', '30', '35', '40', '45', '50'],
    result = numbers.filter(filterNumbers(10, 30));

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

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

Comments

2

You can do something like: numbers.filter(function (value) { return value >= 10 && value <= 30 });

And if you really want the output to be N1 - N2 - N3 ... - NN, just do numbers.filter(function (value) { return value >= 10 && value <= 30 }).join(' - ');

2 Comments

you'd need to cast v to a number
It will be done automatically; the array is made up of strings. Weird JavaScript things, you know...
0

try this

var numbers = ['10','15','20','25','30','35','40','45','50'];  
var output = "";
var getnumbers = function(min,max){
  for (var i = 0; i < numbers.length; i++){
    if(numbers[i] >= min && numbers[i] <= max){
      output += numbers[i] + "-";
    }
  }
};
getnumbers(10,30);
console.log(output);

1 Comment

also yours is very valid
0

JavaScript has inbuilt functions to solve this issue.

let numbers = ['10','15','20','25','30','35','40','45','50'];
// Get all elements between '10' and '30'
let result = numbers.splice(numbers.indexOf('10'),numbers.indexOf('30') + 1);
console.log(result);
// If you want the answer to literally be '10-15-20-25-30'
let resultString = "";
for(const i in result){
    resultString.concat(`${result[i]}-`)
}
console.log(resultString);

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.