5

I have an array of integers like this:

var items = [
  [1, 1, 2, 4],
  [2, 1, 4, 6],
  [5, 6, 4, 1],
  [1, 6, 3, 1]
];

Is there a simple way to find and remove all arrays with specific values in a defined position? For example, if I want to remove all arrays with '1' on the second position, the result should be:

var items = [
  [5, 6, 4, 1],
  [1, 6, 3, 1]
];

If I remove all with '4' on the third position, the result should be:

var items = [
  [1, 1, 2, 4],
  [1, 6, 3, 1]
];

I know I can do this by looping through all elements, but this seems to take quite long when the two-dimensional array is large (>1000 arrays).

1
  • 1
    use Array.filter, combined with a function that looks up values you don't want Commented Dec 29, 2017 at 11:35

1 Answer 1

11

Iterate over the items, use Array#filter function to filter those inner arrays which does not have the given value in the given position.

function filterByPosition(array, number, position) {
   return array.filter(innerArray => innerArray[position - 1] !== number);
}

const items = [
  [1, 1, 2, 4],
  [2, 1, 4, 6],
  [5, 6, 4, 1],
  [1, 6, 3, 1]
];

const newItems1 = filterByPosition(items, 1, 2);
console.log('Items1:', newItems1);

const newItems2 = filterByPosition(items, 4, 3);
console.log('Items2:', newItems2);

Sign up to request clarification or add additional context in comments.

Comments

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.