st123
st123

Reputation: 264

Making sense of javascript solution for sorting an array

Questions : Write a JavaScript function which will take an array of numbers stored and find the second lowest and second greatest numbers.

Not sure how this solution works :

function Second_Greatest_Lowest(arr_num) {
  arr_num.sort(function(x, y) {
    return x - y;
  });
  var uniqa = [arr_num[0]];
  var result = [];

  for (var j = 1; j < arr_num.length; j++) {
    if (arr_num[j - 1] !== arr_num[j]) {
      uniqa.push(arr_num[j]);
    }
  }
  result.push(uniqa[1], uniqa[uniqa.length - 2]);
  return result.join(',');
}

I think I understand what is happening in the loop, but I'm not sure why that is necessary when later uniqa[1] is pushed into the result array. Aren't they performing the same action?

Upvotes: 0

Views: 103

Answers (3)

Omer Cohen
Omer Cohen

Reputation: 141

almost right only the validation you need to do on the array is bigger than 1.

function getSecondLowerAndHighest(arr){
    //make the array me unique numbers
    arr = [...new Set(arr)];
    //array from minimum to maximum
    arr.sort((x,y) => x - y);
    const lower = arr[1];
    //array from maximum to minimum
    arr.reverse();
    const high = arr[1];
    return {lower, high};
}

Upvotes: 1

John
John

Reputation: 6268

var numbers = Array(5, 5,6,3,1,67,8,4,2,421,5,1,1,0,0)

function task(numbers)
{
    // Get the unique items
    numbers = numbers.filter((el, index, arr) => arr.indexOf(el) == index);

    // Sort them
    numbers = numbers.sort((a, b) => a-b);
    
    // Take the ones you want
    return Array(numbers[1], numbers.splice(-2)[0])
}

console.log("Targets: ", task(numbers))

Upvotes: 2

Δ O
Δ O

Reputation: 3710

const myFunction = (arr) => {
  arr = arr
    .filter((v, i, a) => a.indexOf(v) === i) // filter unique values
    .sort() // sort if needed
    
  return [arr[1], arr[arr.length-2]]
}

const [ secondLowest, secondHighest ] = myFunction([6, 3, 6, 5, 2, 1, 2, 4])
console.log(secondLowest, secondHighest)

Upvotes: 0

Related Questions