0

My code is meant to get the least element and remove it from an array and then return the modified array. But in this case My code is supposed to remove 68 from this array

 //[568,333,153,68,359,130,308,323,169]

and return

//[568,333,153,359,130,308,323,169]

but instead removes 68 from the first element (568) and returns

//[5,333,153,68,359,130,308,323,169]

Please i need help on how to fix this problem

here is my code

function remove(arr) {
  let least = Math.min(...arr);
  let strArr = arr.join(' ');
  let regex = new RegExp(least);
  let newArr = strArr.replace(regex, '').split(' ');
  return (newArr.filter((arr) => {
    if ((isNaN(arr) !== true) || arr !== undefined || arr !== ' ') {
      return arr;
    }
  }).map((arr) => parseInt(arr)));
}
remove([568, 333, 153, 68, 359, 130, 308, 323, 169]);

// Returns [5,333,153,68,359,130,308,323,169] instead of 
// [568,333,153,359,130,308,323,169]
Josh
  • 11
  • 4

3 Answers3

4

You can use Filter

let values = [568,333,153,68,359,130,308,323,169];

let filtered = values.filter( item => item !== 68 );

console.log(filtered)
1

Just use array filter and it will return a new array without 68

let x = [568, 333, 153, 68, 359, 130, 308, 323, 169];

let y = x.filter((item) => {
  return item !== 68

})

console.log(y)
brk
  • 43,022
  • 4
  • 37
  • 61
1

You can remove the min value using splice

function remove (arr) {
    let least = Math.min(...arr);
    let index = arr.indexOf(least);
    if (index > -1) {
      arr.splice(index, 1);
    }
    return arr;
}
console.log(remove([568,333,153,68,359,130,308,323,169]));
Vineesh
  • 3,375
  • 15
  • 30