2

I have an array like below:

[
  'author/2020/01/01/all_authors_000.csv',
  'book/2020/01/01/all_books_000.csv',
  'book/2020/01/01/all_books_001.csv',
  'book/2020/01/01/all_books_002.csv',
  'others/2020/01/01/other_stuff.csv',
]

As you can see there are three items that start with the word book. I want to remove all but one, so I end up with something like:

[
  'author/2020/01/01/all_authors_000.csv',
  'book/2020/01/01/all_books_000.csv',
  'others/2020/01/01/other_stuff.csv',
]

How can I achieve this?

4

2 回答 2

3

这是工作示例:

var array = [
   "author/2020/01/01/all_authors_000.csv",
   "book/2020/01/01/all_books_000.csv",
   "book/2020/01/01/all_books_001.csv",
   "book/2020/01/01/all_books_002.csv",
   "others/2020/01/01/other_stuff.csv",
];

var filteredArray = [];
var previous = "";

for (let i of array) {
   if (i.substr(0, i.indexOf("/")) != previous) {
      filteredArray.push(i);
      previous = i.substr(0, i.indexOf("/"));
   }
}

每个循环之前的值"/2020"都存储在previous变量中,if 语句检查该值是否与前一个循环中的值相同。如果没有,它会将其推入filteredArray.

因此filteredArray是没有重复的数组。

于 2021-03-22T07:33:26.720 回答
0

这是另一种方法。基本上是一个函数,它接受你的数组和一个识别重复项的标准(在你的情况下book)。所有这些重复项都将被删除,但第一个。

const array = [
  "author/2020/01/01/all_authors_000.csv",
  "book/2020/01/01/all_books_000.csv",
  "book/2020/01/01/all_books_001.csv",
  "book/2020/01/01/all_books_002.csv",
  "others/2020/01/01/other_stuff.csv",
];

const removeDuplicates = (array, criteria) => {
  return array.filter(
    (path) =>
      ![...array.filter((path) => path.includes(criteria)).splice(1)].includes(
        path
      )
  );
};

console.log(removeDuplicates(array, "book"));

于 2021-03-22T07:57:02.333 回答