How to select all the values ​from my array that have the same number?

Viewed 51

I am currently encountering a problem with tables or I cannot find the answer. So I have an array with only numbers (from 0 to 1). I wonder how to select all the values ​​from my array that have the same number and then store them in a variable.

Example: I want to select all the values ​​of my array with the number 1 to store it in a variable and add methods to it. (It's for a tilemap).

let gameMap = [
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 1, 1, 0, 0, 0, 0, 0, 0,
    0, 0, 1, 1, 0, 0, 1, 1, 0, 0,
    0, 0, 0, 0, 0, 0, 1, 1, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 1, 1, 0, 0, 0, 0,
    0, 0, 0, 0, 1, 1, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 1, 1, 1,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0
];
2 Answers

The values are either 0 or 1. I think you're confusing values with indices. If you wanted to select all the values with the same number, you'd just have an array of zeroes or ones, which doesn't seem very useful.

From what I can gather, you want to save the indices that contain the value 1 so you can do something with them. If that is the case, something like below should work:

let gameMap = [
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 1, 1, 0, 0, 0, 0, 0, 0,
    0, 0, 1, 1, 0, 0, 1, 1, 0, 0,
    0, 0, 0, 0, 0, 0, 1, 1, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 1, 1, 0, 0, 0, 0,
    0, 0, 0, 0, 1, 1, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 1, 1, 1,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0
];

idxs = gameMap.map((v, k) => {
    if (v === 1) { return k }
}).filter(Number)

console.log(idxs)

Here, map is used to call a function to check if each value is 1, and if it is, return the index of the array. You can then filter on the resulting array to get rid of the undefined values that appear.

If you actually did just want all the ones in your array however, it's a lot easier, though I'm not sure what use it would be.

let ones = gameMap.filter(x => x === 1)

You can simply achieve it by using Array.filter() method along with Array.reduce()

Live Demo :

let gameMap = [
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 1, 1, 0, 0, 0, 0, 0, 0,
    0, 0, 1, 1, 0, 0, 1, 1, 0, 0,
    0, 0, 0, 0, 0, 0, 1, 1, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 1, 1, 0, 0, 0, 0,
    0, 0, 0, 0, 1, 1, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 1, 1, 1,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0
];

const searchNumber = 1;

const filteredArr = gameMap.filter(n => n === searchNumber);

const count = filteredArr.reduce((a, b) => a + b);

console.log(count);

Related