Home > Software design >  How can I return "1-5" if the array is [1,2,3,4,5] in JavaScript?
How can I return "1-5" if the array is [1,2,3,4,5] in JavaScript?

Time:11-11

I am trying to make a program that returns ["1-5"] if I give [1,2,3,4,5].

I have made it but I can't filter it. So I want a code that will filter my output code. Or any code that is better than mine.

let array = [1,2,3,5,6,7,8,10,11, 34, 56,57,];
let x = [];

for(let i = 0; i < array.length; i  ){
  for(let j = 0; j < array.length; j  ){
    if(array[i]   j == array[j]){
       x.push(array[i]   "-"   array[j]);
    }
    if(array[j] > array[i]   j && array[j   1]){
      let y = array.slice(j, array.length)
      array = y;
      i, j = 0;
    }
    if(array[i] - array[i   1] != -1 && array[i   1] - array[i] != 1 && array[i   1] != undefined){
      x.push(array[i]);
    }
  }
}

console.log(x);

CodePudding user response:

If you assume that the list is sorted, we only need to traverse the list sequentially. There's no need to have double-nested loops. If you maintain sufficient states, you can determine whether you are in a group and you merely manage the start versus the last element in the group.

To simplify things I made use of ES6 string interpolation ${start}-${last}.

let array = [1,2,3,5,6,7,8,10,11, 34, 56,57];
let result = [ ];
let hasStart = false;
let start = 0;
let last = 0;
for (let num of array) {
    if (!hasStart) {
        hasStart = true;
        last = start = num;
        continue;
    }
    if (num === last   1) {
        last = num;
        continue;
    }
    result.push( start === last ? start : `${start}-${last}` );
    last = start = num;
}
if (hasStart) {
    result.push( start === last ? start : `${start}-${last}` );
}
console.log(result);

CodePudding user response:

Input: [1,2,3,4,5]

Output: ["1-5"]

So I assume you want to get string in format: ["smallestelement-largestelement"]

var input1 = [1,2,3,4,5]
console.log( "[" '"' Math.min(...input1) "-" Math.max(...input1) '"' "]")

If what you want is string in format: ["firstelement-lastelement"]

var input1 = [1,2,3,4,5]
console.log( "[" '"' input1[0] "-" input1.pop() '"' "]")

CodePudding user response:

let min = Number.MAX_VALUE
let max = Number.MIN_VALUE

arr.forEach((element) => {
   if(element > max) max = element
   if(element < min) min = element
}

console.log(`${min} - ${max}`)

CodePudding user response:

If you have an integer array, and if you want to output the range, you could natively sort() it (you can also provide rules for sorting) and use shift() for the first element and slice(-1) for the last:

let arr = [4,1,5,3].sort();
console.log(arr.shift() '-' arr.slice(-1));

As said in the comments, you should clarify if you wish "1-57" for the snippet array, or describe your use case more broadly.

CodePudding user response:

The phrasing of the question makes this somewhat difficult to answer, but based on your code snippet I can gather that you are either:

  1. Attempting to find the range of the entire array OR
  2. Attempting to find contiguous ranges within the array

Based on these interpretations, you could answer this question as follows:

function detectRange(a) {
  // clone a
  const b = [...a]
  // remove first value
  const min = max = b.splice(0, 1)[0]

  // compute range
  const range = b.reduce(({min, max}, i) => {
    if(i < min) min = i
    if(i > max) max = i
    return { min, max }
  }, {min, max})

  return range
}

function detectRanges(a) {
  // clone a
  const b = [...a]
  // remove first value
  const min = max = b.splice(0, 1)[0]

  // init ranges array
  const ranges = [ ]
  // compute ranges
  const range = b.reduce(({min, max}, i) => {
    if(i === max   1) {
      return {min   , max: i}
    } else {
      ranges.push({min, max})
      return {min: i, max: i}
    }
  }, {min, max})
  // push the remaining range onto the array
  ranges.push(range)

  return ranges
}

function printRange(r) {
  console.log(`["${r.min}-${r.max}"]`)
}

function printRanges(r) {
  r.forEach(i => {
    printRange(i)
  })
}

// detect and print range of whole array
printRange(detectRange([1, 2, 3, 5, 6, 7, 8, 10, 11, 34, 56, 57]))
// detect and print only contiguous ranges within array
printRanges(detectRanges([1, 2, 3, 5, 6, 7, 8, 10, 11, 34, 56, 57]))

CodePudding user response:

const array = [1, 2, 3, 5, 6, 7, 8, 10, 11, 34, 56, 57];

let s = null, d = 0;

const result = array.sort((a, b) => a - b).reduce((p, c, i, arr) => {
    d  ;
    if (!s) s = c;
    if (arr[i   1] - s > d) {
        s === c ? p.push(s) : p.push(`${s}-${c}`);
        s = null;
        d = 0;
    }
    if (!arr[i   1]) s === c ? p.push(s) : p.push(`${s}-${c}`);

    return p;
}, []);

console.log(result);

  • Related