You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从仅含0和1的数组中筛选相同数值元素并存储到变量?

从0/1数组中筛选指定值元素的解决方案

基础筛选方法

JavaScript的Array.filter()方法可直接完成筛选需求,它会遍历数组并返回所有符合条件的元素组成的新数组。

筛选所有值为1的元素:

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
];

// 筛选值为1的元素
let ones = gameMap.filter(item => item === 1);

若需筛选值为0的元素,只需将条件改为item === 0。

扩展:结合tilemap需求添加自定义方法

如果需要在筛选结果上添加tilemap相关实用方法(比如获取元素在地图中的行列坐标),可通过以下两种方式实现:

方式1:为筛选结果直接添加方法

适合快速开发场景,直接给筛选后的数组挂载自定义方法:

// 筛选包含原索引的1元素
let onesWithIndex = gameMap.reduce((acc, item, index) => {
  if (item === 1) {
    acc.push({ value: item, index: index });
  }
  return acc;
}, []);

// 添加获取tile行列坐标的方法(默认每行10个tile,可按需修改)
onesWithIndex.getTilePositions = function(tileRowLength = 10) {
  return this.map(el => ({
    row: Math.floor(el.index / tileRowLength),
    col: el.index % tileRowLength
  }));
};

// 使用方法获取所有1的坐标
let tilePositions = onesWithIndex.getTilePositions();
console.log(tilePositions); // 输出格式示例:[{row:2, col:2}, {row:2, col:3}, ...]

方式2:封装成可复用工具对象

如果需要在多个tilemap场景中复用逻辑,可封装为独立工具对象,避免污染数组原型:

const TileFilter = {
  // 从数组筛选指定值元素,附带索引和坐标方法
  getTileGroup: function(array, targetValue, tileRowLength = 10) {
    const group = array.reduce((acc, item, index) => {
      if (item === targetValue) {
        acc.push({ value: item, index: index });
      }
      return acc;
    }, []);

    // 添加获取坐标的方法
    group.getPositions = function() {
      return this.map(el => ({
        row: Math.floor(el.index / tileRowLength),
        col: el.index % tileRowLength
      }));
    };

    return group;
  }
};

// 使用示例
let onesGroup = TileFilter.getTileGroup(gameMap, 1);
let positions = onesGroup.getPositions();

这些方法可直接用于tilemap开发,比如根据坐标绘制特定tile、设置碰撞区域等。

内容的提问来源于stack exchange,提问作者Karloux

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 06:20:43