Filter repeated fields in a two-dimensional object array in javascript and keep only unique values (array.filter and Array.from)

Filter repeated fields in a two-dimensional object array in javascript and keep only unique values

1.Array.filter filtering

In JavaScript, you can use Array.filter()the and Setdata structure to filter duplicate fields in a two-dimensional array of objects, keeping only unique values. Here's one possible way to write it:

// 示例数据
const array = [
  {
    
     id: 1, name: 'John' },
  {
    
     id: 2, name: 'Jane' },
  {
    
     id: 3, name: 'John' },
  {
    
     id: 4, name: 'Alice' },
  {
    
     id: 5, name: 'Jane' }
];

// 使用 Set 过滤数组
const uniqueArray = array.filter((obj, index, self) =>
  index === self.findIndex((o) => (
    o.name === obj.name
  ))
);

console.log(uniqueArray);

insert image description here

In the above example, we use Array.filter()the method to iterate through the array and use Array.findIndex()the method to find the index position of the first object with the same name as the current object. In this way, only the first occurrence of the object will be kept, and subsequent duplicate objects will be filtered out, resulting in an uniqueArrayarray containing only unique values.

The output is as follows:

[
  {
    
     id: 1, name: 'John' },
  {
    
     id: 2, name: 'Jane' },
  {
    
     id: 4, name: 'Alice' }
]

Note: The above method will only filter objects with the same field (here name), which in this case will not filter the same idfield. If you want to filter based on multiple fields, you can Array.findIndex()add appropriate condition judgments in the callback function.

array.filter()method

array.filter()is an array method used to create a new array containing all elements that satisfy the specified criteria. It takes a callback function as an argument and calls that function on each array element. The callback function needs to return a boolean value to determine whether to keep the element.

array.filter()The syntax is as follows:

array.filter(callback(element[, index, [array]])[, thisArg])

in:

  • callback: required, indicates the function to test each element.
    • element: The element currently being processed.
    • index(optional): The index of the current element in the array.
    • array(Optional): filterAn array of methods to call.
  • thisArg(Optional): The value used to execute the callback function this.

Here is a simple example showing how to use array.filter()the method:

const numbers = [1, 2, 3, 4, 5];

const evenNumbers = numbers.filter((num) => num % 2 === 0);

console.log(evenNumbers); // [2, 4]

In the above example, we defined a callback function (num) => num % 2 === 0that tests whether each number is even. array.filter()method iterates over each element in the array and applies the callback function to each element. Only when the callback function returns true, the corresponding elements will be preserved in the new array evenNumbers.

Note that array.filter()a new array of elements satisfying the condition will be returned, and the original array will not be affected.

2.Array.from filter

const arr = [
  {
    
     id: 1, name: 'John' },
  {
    
     id: 2, name: 'Jane' },
  {
    
     id: 3, name: 'John' },
  {
    
     id: 4, name: 'Kate' },
  {
    
     id: 5, name: 'Jane' }
];

// 使用Set和map进行去重
const uniqueArr = Array.from(new Set(arr.map(obj => obj.name))).map(name => {
    
    
  return arr.find(obj => obj.name === name);
});

console.log(uniqueArr);

insert image description here

Array.frommethod

Use Array.fromthe method to convert an array-like object or iterable object into an array. Its syntax is as follows:

Array.from(arrayLike[, mapFn[, thisArg]])

in:

  • arrayLike: The array-like object or iterable to convert to an array.
  • mapFn(Optional): A mapping function that operates or transforms each element.
  • thisArg(optional): Optionally sets thisthe value in the mapping function.

Here are some examples that demonstrate Array.fromthe notation used in different situations:

  1. Convert an array-like object to an array:
const arrayLike = {
    
     0: 'a', 1: 'b', 2: 'c', length: 3 };
const array = Array.from(arrayLike);

console.log(array); // ['a', 'b', 'c']
  1. Operate on iterable objects:
const iterable = 'hello';
const array = Array.from(iterable, char => char.toUpperCase());

console.log(array); // ['H', 'E', 'L', 'L', 'O']
  1. Use an arrow function to set thisthe value:
const arrayLike = {
    
     0: 'a', 1: 'b', 2: 'c', length: 3 };
const array = Array.from(
  arrayLike,
  function (element) {
    
    
    // this 指向 object
    return element.toUpperCase() + this.postfix;
  },
  {
    
     postfix: '!' }
);

console.log(array); // ['A!', 'B!', 'C!']

The above is Array.fromthe basic usage. mapFnYou can adjust and parameters according to specific needs thisArg, so as to perform further operations and processing on the converted array.


@ Leak sometimes

Guess you like

Origin blog.csdn.net/weixin_41290949/article/details/131743789