Проверьте, равны ли хотя бы два значения массива - PullRequest
0 голосов
/ 16 сентября 2018

Я на самом деле ищу способ проверить, равны ли два значения массива или более. Вот несколько примеров:

[1, 2, 3] // false
[1, 1, 5] // true
['a', 'b', 'a', 'c'] // true
[10, 10, 10] // true

Я нашел эту функцию, которая выдает 'true', если КАЖДЫЕ значения массива равны, но это не то, что я хотел бы:

[1,1,1,1].every( (val, i, arr) => val === arr[0] ) // true

Ответы [ 12 ]

0 голосов
/ 16 сентября 2018
function isSameArray(data, count) {
   var result = false;
   data.forEach(a => {
      const filter = data.filter(f => f === a); 
      if (filter.length > count - 1) {
         result = true;
         return;
      }
   });

   return result;
}

isSameArray([1, 2, 3], 2)
0 голосов
/ 16 сентября 2018

Используя цикл for, мы можем разорвать цикл, когда найдем дубликат.

var a = [1, 2, 3] // false
var b = [1, 1, 5] // true
var c = ['a', 'b', 'a', 'c'] // true
var d = [10, 10, 10] // true


function diff(arr){

    var diff = []
    
    for(let i = 0; i<arr.length; i++){
        if(diff.includes(arr[i])){
         return true;//<-- break the loop   
        }else{
            diff.push(arr[i]);
        }
    }

    return false;

}

console.log(diff(a))
console.log(diff(b))
console.log(diff(c))
console.log(diff(d))
0 голосов
/ 16 сентября 2018

Сокращение массива в объект с ключами, являющимися элементами. Если ключи объекта имеют длину, отличную от длины элементов, существуют дубликаты.

Здесь также указывается количество дубликатов.

const items1 = [1, 2, 3, 3, 4]
const items2 = [1, 2, 3, 3, 3, 3, 4]
const items3 = [1, 2, 3, 4]
const items4 = [undefined, undefined]

function dupCount(array) {
  const obj = array.reduce((acc, item) => {
    acc[item] = true;
    return acc;
  }, {})
  return array.length - Object.keys(obj).length
}

console.log(dupCount(items1))
console.log(dupCount(items2))
console.log(dupCount(items3))
console.log(dupCount(items4))
0 голосов
/ 16 сентября 2018

Вы можете легко зациклить его, используя for loop, например: -

function hasDuplicate(lst){
    for(var i=0; i<lst.length; i++)
        for(var j=i+1; j<lst.length;j++)
            if(i!=j && lst[i] === lst[j])
                return true;
    return false;
}

var list1 = [1,1,5];
window.alert(hasDuplicate(list1)); //True
0 голосов
/ 16 сентября 2018

Array.some работает так же, как Array.every, за исключением того, что если тест проходит значение true для одного из элементов массива, для которого вы выполняете итерацию, выполнение останавливается и возвращается значение true. Вероятно, то, что вы ищете.

0 голосов
/ 16 сентября 2018

Следующее поможет вам в достижении результата, который вы привели в качестве примера:

Array_is_true(int *a,int n)
{
   int j=1,flag=0;
  for(int i=0,i<n;i++)
   {
      j=i+1;
      while(j<n;)
      {
         if(a[i]==a[j])
         { flag=1;j++;}
      }
   }
}
0 голосов
/ 16 сентября 2018

Вы можете найти все уникальные элементы через lodash и просто сравнить размер обоих массивов, чтобы получить то, что вы хотите.

a = [1, 2, 3]
a_uniq = _.uniq(a); //will return [1, 3]
console.log(a.length != a_uniq.length); //will return false

a = [1, 1, 3]
a_uniq = _.uniq(a); //will return [1, 3]
console.log(a.length != a_uniq.length); //will return true

Здесь можно проверить быстро: https://codepen.io/travist/full/jrBjBz/

0 голосов
/ 16 сентября 2018

Добавьте их в набор при проверке с использованием метода find

let items1 = [1, 2, 3, 3, 4];
let items2 = [1, 2, 3, 4];
let items3 = ['a', 'b', 'a', 'c']
let items4 = [0, 0]
let items5 = [undefined, undefined]

function hasDuplicate(array) {
  const set = new Set()
  return array.some(it => {
    if (set.has(it)) {
      return true
    } else {
      set.add(it);
      return false;
    }
  })
}

console.log(hasDuplicate(items1))
console.log(hasDuplicate(items2))
console.log(hasDuplicate(items3))
console.log(hasDuplicate(items4))
console.log(hasDuplicate(items5))
0 голосов
/ 16 сентября 2018

Одним простым способом было бы создать Set уникальных значений и сравнить size из Set в length массива

const hasDuplicates = (arr) => new Set(arr).size < arr.length ;

console.log(hasDuplicates([1, 2, 3]));
console.log(hasDuplicates([1, 1, 5]));
console.log(hasDuplicates(['a', 'b', 'a', 'c']));
console.log(hasDuplicates([10, 10, 10]));
0 голосов
/ 16 сентября 2018

Вы можете использовать Set для устранения дубликатов:

const nonUnique = a => new Set(a).size !== a.length;

console.log(nonUnique([1, 2, 3])); // false
console.log(nonUnique([1, 1, 5])); // true
console.log(nonUnique(['a', 'b', 'a', 'c'])); // true
console.log(nonUnique([10, 10, 10])); // true
...