The array can be any, for example, such [1,1,1,1,2,1,3,1,1,0,1,1,0] . Those. the result should be (2,3) . Who will have any ideas? Help, plyiz)

And then my version pulls up and repeating numbers.

 function unique(arr) { return arr.filter(function (item, index) { return arr.indexOf(item) === index }) } console.log(unique(array)) // [1, 2, 3, 0] 

And if there is an opportunity to explain to the beginner in detail, then there will generally be a fire! Thank you all in advance.

  • one
    Have you tried to do anything? - ThisMan
  • corrected, added its own solution. - Keeps Keeps
  • I wrote my own version, if it suits you, then tick the box next to the answer, or look at other answers - ThisMan

2 answers 2

 const test = [1,1,1,1,2,1,3,1,1,0,1,1,0]; const getUniqElements = (arr) => { const occurrences = {}; // считаем сколько раз каждый элемент встречается в массиве arr.forEach(el => { if(occurrences[el]) occurrences[el]++; else occurrences[el] = 1 }) // берем только те элементы, которые попались 1 раз return Object.keys(occurrences).filter(key => occurrences[key] === 1) } console.log(getUniqElements(test)) 

First, we consider the occurrence of elements in the array, and then we take only those that appear once

    More Varick

     const test = [1, 1, 1, 1, 2, 1, 3, 1, 1, 0, 1, 1, 0], fUnic = (arr) => arr.filter((e, i) => arr.indexOf(e, i + 1) == -1 && arr.lastIndexOf(e, i - 1) == -1); console.log(fUnic(test)); 

    • Why indexOf and lastIndexOf at the same time? - ThisMan
    • Just look at the console output after fUnic = (arr) => arr.forEach ((e, i) => console.log ( ${i}: ${arr.indexOf(e, i + 1) == -1},${arr.lastIndexOf(e, i - 1) == -1} )); `and it will be clear. - user210322
    • "0: false,false" "1: false,false" "2: false,false" "3: false,false" "4: true,true" "5: false,false" "6: true,true" "7: false,false" "8: false,false" "9: false,true" "10: false,false" "11: true,false" "12: true,false" - user210322
    • And then simply Boolean mathematics, that is, only elements that meet the condition true&&true - user210322 will be included in the resulting array
    • one
      only I have a question. Tell me, why do we prescribe i + 1 and i - 1? why can not just be limited to i? Sorry if this is a completely stupid question. I'm just learning - Keeps Keeps