Home > front end >  i want to push arrays into array
i want to push arrays into array

Time:09-26

i have two parameters & two arguments, one of them should be a number & the other should be array, if the number hs similar items in the array i should extract the similar numbers then push them again into the array, with keeping the order of non-similar numbers, i have wrote this code but its not working, i spent more than two days trying to figure this out but no result yet.

function extractNumber(num, nums) {
if(nums.includes(num)===true){
  for (let i = 0; i <nums.length; i  ) {
    if(nums[i]=== num){
     var popped = nums.splice(i,1);
      i--;
      nums.push(popped);
    } 
  }  
}
  return nums;
}

extractNumber(7,   [1,2,7,1,7,1,7,3,7,1]);

CodePudding user response:

Something like this ?

Your title is a bit misleading.

function extractNumber(num, nums) {
  nums.forEach((i, index) => { //loop each item in nums
    if (i === num) { //if current item is same as num
      nums.splice(index, 1) //remove it from its position..
      nums.push(i) //..and push it at the end of the array
    }
  })
  return nums
}


console.log(extractNumber(7, [1, 2, 7, 1, 7, 1, 7, 3, 7, 1]))

  • Related