0

Assuming I have an array

let arr = [
    [0,1,0,4],
    [1,0,1,2],
    [0,0,1,1],
    [0,1,0,1]
];

I want to loop through the array with a higher order array function, and return an array where all values that are not equal to n (in my case let's say n=0) will be stacked against the end of the array:

console.log( arr.map( certainFunction ) );
//returns this;
[ [0,0,1,4],
  [0,1,1,2],
  [0,0,1,1],
  [0,0,1,1] ]

Is it possible using higher order functions to loop through arr and return the array above? Then how will the certainFunction look?

1
  • Does the order matter? Also, does it matter for numbers that are less than n? Commented Mar 3, 2018 at 2:22

3 Answers 3

3

A higher-order func, as ordered ;)

let separate = n => a => a.filter(x => x === n).concat(a.filter(x => x !== n));

//

let arr = [
    [0,1,0,4],
    [1,0,1,2],
    [0,0,1,1],
    [0,1,0,1]
];


newArr = arr.map(separate(1)) // move 1's to the start

console.log(newArr.map(x => x.join()))

or, with some more functional programming:

let eq = a => b => a === b;
let not = f => a => !f(a);

let separate = n => a => a.filter(eq(n)).concat(a.filter(not(eq(n))));
Sign up to request clarification or add additional context in comments.

Comments

1

This can be done linearly by keeping a goalpost and pushing all arr[i] != n back to this index.

function push_to_end (arr, n=0) {
  // Begin by pushing items to the very end.
  let index = arr.length - 1
  for (let i = index; i > -1; i--) {
    // If you encounter an integer not equal to end, place it
    // at `index` and move the goalpost back one spot.
    if (arr[i] !== n)
      arr[index--] = arr[i]
  }

  // Fill everything up to the goalpost with `n`, as that is how
  // many times we observed n.
  for (let i = 0; i <= index; i++) {
    arr[i] = n
  }

  return arr
}

In your case, you would apply this function to each array in your array of arrays:

arr.map(a => push_to_end(a, n))

Comments

0

Array.prototype.sort()

let arr = [
    [0,1,0,4],
    [1,0,1,2],
    [0,0,1,1],
    [0,1,0,1]
];

arr = arr.map(ar => ar.sort((a, b) => a-b));
console.log(arr)

Works in your case, not sure if you wanted numbers less than n to work too

3 Comments

This is much slower than it needs to be.
slower? How big are these arrays? Have you considered something like a database, or are you counting milliseconds?
You don't need to sort the arrays. Plus, sorting is not necessarily the correct answer, e.g. if there are negative integers or if n=2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.