查找单个数组元素之间的交集

时间:2018-11-06 20:41:18

标签: javascript arrays

我有一个像这样的数组

[".a",".acc",".as",".b",".bad",".ca",".cat"]

应该以长字符串搜索这些数组元素。

fire consumed his plane. AAC was required to have two persons. A third employee who was present at the airport. As a result, Richard was unable to escape

因此,当它搜索".acc"时,只会找到一个结果。但是,当它搜索".a"时会发现三个结果。现在结果正在重复,这很麻烦。

我想要某种方法从此数组中删除元素".acc"".as"并将"a"保留在数组中,以便只能搜索".a"

这是数组元素之间的某种交集。但我想不出解决此问题的直接方法。

摘要:我在数组中有三个具有相同起始字符(.a)的项目。我想保持项目的长度最小,并删除其他两个。

3 个答案:

答案 0 :(得分:2)

这将用原始数组中不重叠的字符串填充z

let z = [];
let cur;
['.a', '.acc', '.as', '.b', '.bad', '.ca', '.cat'].sort().forEach((x) => {
  if (!x.startsWith(cur)) {
      z.push(x);
      cur = x
  }
})

(仅当原始数组未必总是已排序时才需要sort()调用。)

答案 1 :(得分:2)

使用Array.filter()来迭代数组。使用Array.every()检查该元素是否不是startsWith所有其他元素(自身除外)。

const arr = [".a",".acc",".as",".b",".bad",".ca",".cat"];

const result = arr.filter(s1 => 
  arr.every(s2 => 
    s1 === s2 || !s1.startsWith(s2)
  )
);

console.log(result);

ES5版本:

var arr = [".a",".acc",".as",".b",".bad",".ca",".cat"];

var result = arr.filter(function(s1) {
  return arr.every(function(s2) {
    return s1 === s2 || !s1.startsWith(s2);
  });
});

console.log(result);

答案 2 :(得分:0)

let inputString = ".a .as .as .acc .acc .acc REST OF STRING...";

let keywords = [".a", ".acc", ".as", ".b", ".bad", ".ca", ".cat"];

function getOccurrenceOfKeyword(searchString, keyword) {
  return searchString.split(keyword).length - 1;
}

function matchingKeywordsOccurrence(searchString, searchKeyword) {
  let matchingKeywordsOccurrence = 0;
  keywords.forEach(keyword => {
    if (keyword.startsWith(searchKeyword) && keyword !== searchKeyword) {
      matchingKeywordsOccurrence += getOccurrenceOfKeyword(
        searchString,
        keyword
      );
    }
  });
  return matchingKeywordsOccurrence;
}

function findExclusiveOccurrenceOfKeyword(searchString, searchKeyword) {
  let keywordOccurrence = getOccurrenceOfKeyword(searchString, searchKeyword);
  return (
    keywordOccurrence - matchingKeywordsOccurrence(searchString, searchKeyword)
  );
}

console.log(findExclusiveOccurrenceOfKeyword(inputString, ".a"));
console.log(findExclusiveOccurrenceOfKeyword(inputString, ".as"));
console.log(findExclusiveOccurrenceOfKeyword(inputString, ".acc"));