javascript practical questions
- Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.
// input: [false,1,0,1,2,0,1,3,"a"] // output: [false,1,1,2,1,3,"a",0,0] var moveZeros = function (arr) { return [ ...(arr.filter(n => n !== 0)), ...(arr.filter(n => n === 0)) ]; }
2. Find all pairs in an array of integers whose sum is equal to a given number.
// input: array=[2,3,12,3,5,0,8,23,-1,2]; sum=5 // output: [2, 3],[2, 3],[3, 2],[3, 2], 5, 0] function findPairsWithSum(arr, S) { const sum = []; for(let i = 0; i< arr.length; i++) { for(let j = i+1; j < arr.length; j++) { if(S == arr[i] + arr[j]) sum.push([arr[i],arr[j]]) } } return sum }