Home > Software design >  Return a new array thats greater than its 2nd value. If the array has less than two elements, have t
Return a new array thats greater than its 2nd value. If the array has less than two elements, have t

Time:12-20

How to return a new array with the array values that are greater than its 2nd value. If the array that was passed to the function has less than two elements, have the function return false.

For example, greaterThanSecond([1,3,5,7]) should return [5, 7]. Similarly, greaterThanSecond([0, -3, 2, 5]) should return [0, 2, 5]. Also, greaterThanSecond([2]) should return false.

I tried

function valGreaterThanSecond(arr) {
  for (let newArr of arr) {
    if (newArr > arr[1]) {
      return [newArr]
    }else {
        return false
        }
    }
 }

CodePudding user response:

You can try a one-liner:

[0, -3, 2, 5].filter((element, index, array) => element > array[1])

The filter function has 3 parameters:

  1. The inspected elment
  2. Index of the inspected element
  3. The original array

The filter iterate through the array and you can compare to the original array's second element

CodePudding user response:

function valGreaterThanSecond(arr) {
  
  let resultArray = []
  console.log(arr.length)
  let checkValue = arr[1]
  if(arr.length < 2)
  return false
  else
  {
  for(let i = 0 ; i < arr.length ; i  ){
      if(arr[i]!=checkValue && arr[i]>checkValue)
      resultArray.push(arr[i])
  }
  return resultArray
}
 }
console.log(valGreaterThanSecond([2]))

try this approach

CodePudding user response:

You can try this

function greaterThanSecond(arr) {
    if (arr.length < 2)
        return false;
    return arr.filter((item) => item > arr[1])
}
console.log(greaterThanSecond([0,-3,2,5]))

CodePudding user response:

You can try this:

const greaterThanSecond = arr => {
   if (arr.length > 1){ 
      return arr.filter(e => e > arr[1])
   }
   return false
}
console.log(greaterThanSecond([1,3,5,7]))

In this function, at first you should check if the length of the array is not less than 2. Then we filter the array by checking if each number in the array is bigger than the second number and keep those ones in the array.

  • Related