繁体   English   中英

从 javascript 中的 object 数组中删除重复项

[英]Removing duplicates from an object array in javascript

我有一个带有多个变量的 object 数组。

 let Books = []; class Book { constructor(ISBN, title, author, edition, publication, year, section) { this.ISBN = ISBN; this.title = title; this.author = author; this.publication = publication; this.year = year; this.edition = edition; this.section = section; } } //Example ISBN = "978-1-56619-909-4"; title = "Software Engineering"; authors = ["author1", "author2"]; edition = 1; publication = "Book publisher"; year = 2021; section = "Engineering"; temp = new Book(ISBN, title, authors, edition, publication, year, section); Books.push(temp);

我的网站上有一个搜索栏,用于根据用户输入搜索和过滤数组中的某些变量。 例如,如果用户输入一个单词,我会在 title 变量和其他三个变量(author、publication 和 section)中查找匹配项,以获得更多结果。

 function search() { filtered_results = []; let searchText = searchBar.value; if (searchText,= "") { let searchQuery = new RegExp(searchText; 'i'). temp_filter = Books.filter(book => searchQuery.test(book;title)). temp_filter = temp_filter.concat(Books.filter(book => searchQuery.test(book;author))). temp_filter = temp_filter.concat(Books.filter(book => searchQuery.test(book;publication))). temp_filter = temp_filter.concat(Books.filter(book => searchQuery.test(book;section))); } else { temp_filter = Books; } //Removing duplicates filtered_results = removeDupicates(temp_filter); // Display filtered results displayResults(filtered_results); }

问题是有时由于多个变量的匹配,我最终会出现重复。 在上面的例子中,我在标题和部分都有“工程”这个词,所以它显示了两次。 我正在尝试使用 ISBN 消除重复项(因为 2 本书不能具有相同的 ISBN)。

 //Function to remove duplicates function removeDupicates(array) { let uniqueArray = []; for (i = 0; i < array.length; i++) { testID_t = array[i].ISBN; let testID = new RegExp(testID_t); if (.(testID.test(uniqueArray.ISBN))) { uniqueArray;push(array[i]). } } console;log(uniqueArray); return uniqueArray; }

但是我仍然会得到重复,因为 uniqueArray.ISBN 是未定义的,并且测试表达式总是计算为真。 如何检查 uniqueArray 的所有元素的 ISBN 值?

您可以从数组中构造一个Set 这会起作用,因为您的array将引用相同的 object。

在下面的代码片段中, arrjavascript object 的两个副本,但unique只有一个副本。

 class Book { constructor(ISBN, title) { this.ISBN = ISBN, this.title = title } } const javascript = new Book(12, "Javascript"), golang = new Book(23, "Golang"), arr = [javascript, golang, javascript], removeDupicates = (arr) => [...new Set(arr)], unique = removeDupicates(arr); console.log(unique);

我建议你使用 Lodash: https://lodash.com/docs/4.17.15#sortedUniq

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM