0

I want to solve the given problem to make reasoning about higher order functions easier for me in the future. Given an array of ones and zeroes, we need to find the elements that are surrounded by ones.

//             0 1 2 3 4 5 6 7 8 9101112
const bombfield = [0,0,1,1,0,0,1,0,1,1,1,0,1];
//The above array has 3 bombs, being 0 1 and 0 at positions 7, 9, and 11.
//What I want to do is filter the array for the bombs, using a function such as this:
const bombs = bombfield.filter((x) => (y) => (z) => (x == 1 && z == 1));
// What I expect this to return through currying is those elements that have 1 as each of their neighbors.
1
  • How does that function get the neighbor elements? Commented Apr 13, 2022 at 22:34

3 Answers 3

1

There's no currying going on here. bombfield.filter() just checks whether the return value of the callback function is truthy or not. If the returned value is a function, it won't call it again. Since all functions are truthy, this filter succeeds for every element, and just returns a copy of the array.

And even if it did, it wouldn't call it with surrounding elements.

The second argument to the callback function is the array index, and the third argument is the array being filtered. You can use that to access other elements of the same array.

const bombfield = [0,0,1,1,0,0,1,0,1,1,1,0,1];

const bombs = bombfield.filter((x, i, arr) => arr[i-1] === 1 && arr[i+1] === 1);
console.log(bombs);

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

Comments

0

As Barmer said, you don't have to curry anything here, There is a way to get the indexes which you may need as well.

const bombfield = [0,0,1,1,0,0,1,0,1,1,1,0,1];
const bombIndexes = [];

bombfield.forEach((element, index, array) => {
  if (array[index-1] === 1 && array[index+1] === 1) bombIndexes.push(index);
});

const bombs = bombfield.filter((element, index, array) => array[index-1] === 1 && array[index+1] === 1);

console.log("Bomb Indexes: ", bombIndexes);
console.log("Bomb Values: ", bombs);

Comments

0

For an array of the indices which meet your conditions, try

const bombfield = [0,0,1,1,0,0,1,0,1,1,1,0,1];
const bombs = bombfield.map((b, i, a) => a[i - 1] && a[i + 1] && i).filter(b => b);
console.log(bombs);

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.