“JavaScript Array Unik Objek berdasarkan Properti” Kode Jawaban

Objek unik dalam array javascript

const array =
  [
    { "name": "Joe", "age": 17 },
    { "name": "Bob", "age": 17 },
    { "name": "Carl", "age": 35 }
  ]

const key = 'age';

const arrayUniqueByKey = [...new Map(array.map(item =>
  [item[key], item])).values()];

console.log(arrayUniqueByKey);

   /*OUTPUT
       [
        { "name": "Bob", "age": 17 },
        { "name": "Carl", "age": 35 }
       ]
   */

 // Note: this will pick the last duplicated item in the list.
Tame Tapir

Dapatkan nilai unik dari array objek JavaScript

const data = [
  { group: 'A', name: 'SD' }, 
  { group: 'B', name: 'FI' }, 
  { group: 'A', name: 'MM' },
  { group: 'B', name: 'CO'}
];
const unique = [...new Set(data.map(item => item.group))]; // [ 'A', 'B']
Jittery Jay

JavaScript peta return array dengan nilai distinc

//ES6
let array = [
  { "name": "Joe", "age": 17 },
  { "name": "Bob", "age": 17 },
  { "name": "Carl", "age": 35 }
];
array.map(item => item.age)
  .filter((value, index, self) => self.indexOf(value) === index)

> [17, 35]
DevPedrada

JavaScript Array Unik Objek berdasarkan Properti

const array =
  [
    { "name": "Joe", "age": 17 },
    { "name": "Bob", "age": 17 },
    { "name": "Carl", "age": 35 }
  ]

function uniqueByKey(array, key) {
  return [...new Map(array.map((x) => [x[key], x])).values()];
}

console.log(uniqueByKey(array, 'age'));
Jeff Le

JavaScript mendapatkan nilai unik dari kunci

const unique = [...new Set(array.map(item => item.age))];
Defiant Dormouse

Temukan objek unik dalam array objek di JavaScript 5

var array = [{"name":"Joe", "age":17}, {"name":"Bob", "age":17}, {"name":"Carl", "age": 35}];
var unique = [];
var distinct = [];
for(var i = 0; i < array.length; i++ ){
  if(!unique[array[i].age]){
    distinct.push(array[i]);
    unique[array[i].age] = 1;
  }
}


gs.info(distinct);
Wild Weasel

Jawaban yang mirip dengan “JavaScript Array Unik Objek berdasarkan Properti”

Pertanyaan yang mirip dengan “JavaScript Array Unik Objek berdasarkan Properti”

Lebih banyak jawaban terkait untuk “JavaScript Array Unik Objek berdasarkan Properti” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya