使用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
相关产品推荐
相关产品推荐

