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

使用jQuery筛选数组:保留DogName的最新唯一条目

解决方案:保留每个DogName的最新唯一条目

JavaScript 实现

const dogs = [
    { "DogName": "Max", "DogBreed": "GermanShepherd" },
    { "DogName": "Blitz", "DogBreed": "GoldRet" },
    { "DogName": "Max", "DogBreed": "Shitzu" }
];

// 遍历数组,用对象记录每个DogName的最新条目
const latestDogs = Object.values(dogs.reduce((acc, current) => {
    acc[current.DogName] = current; // 后续同名条目自动覆盖旧值
    return acc;
}, {}));

console.log(latestDogs);

PHP 实现(针对你尝试的foreach/inarray场景)

$dogs = [
    ["DogName" => "Max", "DogBreed" => "GermanShepherd"],
    ["DogName" => "Blitz", "DogBreed" => "GoldRet"],
    ["DogName" => "Max", "DogBreed" => "Shitzu"]
];

$latestDogs = [];
foreach ($dogs as $dog) {
    // 以DogName为键存储,后续条目覆盖前面的同名项
    $latestDogs[$dog['DogName']] = $dog;
}
// 重置数组索引(可选,按需使用)
$latestDogs = array_values($latestDogs);

print_r($latestDogs);

核心逻辑说明

不管用哪种语言,核心思路都是利用键的唯一性覆盖旧值:

  • 遍历原数组时,用DogName作为存储结构的键
  • 后续出现的同名条目会直接覆盖之前的条目,最终保留的就是每个DogName最后出现的最新条目
  • 最后将存储结构的值提取为数组,得到目标结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 05:50:44