0

Dear all I'm trying to find non repeated value in an array using javascript.I have written some code but it not working properly ..can you guys tell me where is the problem.thanks.

var arr = [-1, 2, 5, 6, 2, 9, -1, 6, 5, -1, 3];
var n = arr.length;
var result = '';

function nonrep() {
  for (var i = 0; i < n; i++) {
    var j;
    for (j = 0; j < n; j++)
      if (i != j && arr[i] == arr[j]) {
        result = arr[i];
        break;
      }
    if (j == n)
      return arr[i];
  }
  return result;
}
console.log(nonrep())
Anil kumar
  • 21
  • 1
  • 2
  • 3

16 Answers16

5

There is possibly a more neat approach to this solution, but this works as expected by filtering the array and compare it's current value with the array items itself (expect current item's index value).

const sampleArray = [1,2,3,7,2,1,3];
const getNonDuplicatedValues = (arr) => 
    arr.filter((item,index) => {
      arr.splice(index,1)
      const unique = !arr.includes(item)
      arr.splice(index,0,item)
      return unique
  })

console.log("Non duplicated values: " , ...getNonDuplicatedValues(sampleArray))
Manu
  • 183
  • 2
  • 11
4

Some changes:

  • Move all variable declarations inside of the function.
  • Use a function parameter for the handed over array, keep the function pure.
  • Declare all needed variables at top of the function in advance.
  • Take an array as result array unique.
  • Check i and j and if equal continue the (inner) loop.
  • Check the value at i and j and exit the (inner) loop, because a duplicate is found.
  • Take the check at the end of the inner loop and check the index j with the length of the array l, and if equal push the value to unique.
  • Use a single return statement with unique array at the end of the outer loop.

function getUnique(array) {
    var l = array.length,
        i, j,
        unique = [];

    for (i = 0; i < l; i++) {
        for (j = 0; j < l; j++) {
            if (i === j) {
                continue;
            }
            if (array[i] === array[j]) {
                break;
            }
        }
        if (j === l) {
            unique.push(array[i]);
        }
    }
    return unique;
}

console.log(getUnique([-1, 2, 5, 6, 2, 9, -1, 6, 5, -1, 3]));

Another solution could be to check if indexOf and lastIndexOf returns the same value. Then you found a unique value.

var array = [-1, 2, 5, 6, 2, 9, -1, 6, 5, -1, 3],
    unique = array.filter((v, i) => array.indexOf(v) === array.lastIndexOf(v));

console.log(unique);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 2
    Although as always you bring to light fascinating concepts, this time I will have to point the O(2N^2) complexity is redundant. Just an observation though. – Attersson Jun 14 '18 at 10:28
2

 const arr = [-1, 2, 5, 6, 2, 9, -1, 6, 5, -1, 3];
    
    
    const non_repeating = arr.filter(num => arr.indexOf(num) === arr.lastIndexOf(num))
    
    console.log(non_repeating)
1

You could first use reduce to get one object with count for each number element and then filter on Object.keys to return array of non-repeating numbers.

var arr=[-1,2,5,6,2,9,-1,6,5,-1,3];
var obj = arr.reduce((r, e) => (r[e] = (r[e] || 0) + 1, r), {});
var uniq = Object.keys(obj).filter(e => obj[e] == 1).map(Number)

console.log(uniq)

Solution with for loop.

var arr = [-1, 2, 5, 6, 2, 9, -1, 6, 5, -1, 3];

var uniq = [];
for (var i = 0; i < arr.length; i++) {
  for (var j = 0; j < arr.length; j++) {
    if (arr[i] == arr[j] && i != j) break;
    else if (j == arr.length - 1) uniq.push(arr[i])
  }
}

console.log(uniq)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
1

Another simple approach

var arr = [1,1,2,3,3,4,4,5];

let duplicateArr = [];
var repeatorCheck = (item) => {
  const currentItemCount = arr.filter(val => val=== item).length;
  if(currentItemCount > 1) duplicateArr.push(item);
  return currentItemCount;
}
var result = arr.filter((item,index) => {
  var itemRepeaterCheck = !duplicateArr.includes(item) && repeatorCheck(item);
  if(itemRepeaterCheck === 1){
    return item;
  }
});
console.log(result);
shabarinath
  • 548
  • 3
  • 18
1

let arr = [1, 2, 1, 3, 3, 5];

    function nonRepeatableNo(arr) {
        let val = []
        for (let i = 0; i < arr.length; i++) {
            let count = 0;
            for (let j = 0; j < arr.length; j++) {
                if (arr[i] === arr[j]) {
                    count += 1
                }
            }
            if (count === 1) {
                val.push(arr[i])
            }
        }
        console.log(val)
    }
    nonRepeatableNo(arr)
Gaurav
  • 11
  • 3
0

Filtering only unique elements according to OP request:

This uses for loops, as requested. It returns an array containing only elements appearing once in the original array.

var arr = [-1, 2, 5, 6, 2, 9, -1, 6, 5, -1, 3];
var n = arr.length;
var result = [];

function nonrep() {
  for (var i = 0; i < n; i++) {
    for (var j=0 ; j < n; j++)
      if (i!=j && arr[i]==arr[j])
        break;
    if(j==n)
        result.push(arr[i]);
  }
  return result;
}
console.log(nonrep())
Community
  • 1
  • 1
Attersson
  • 4,755
  • 1
  • 15
  • 29
0
var arr1 = [45, 4,16,25,45,4,16, 9,7, 16, 25];
 var arr=arr1.sort();
  console.log(arr);
 var str=[];
 arr.filter(function(value){

if( arr.indexOf(value) === arr.lastIndexOf(value))
{ str.push(value);
console.log("ntttttttttttttnnn" +str)

}// how this works ===============A
 })

O/P

 7,9
Tested
  • 761
  • 4
  • 16
  • 38
0
Please try the below code snippet.

var arr = [-1, 2, 5, 6, 2, 9, -1, 6, 5, -1, 3];
    var uniqArr = [];
    for (var i = 0; i < arr.length; i++) {
      for (var j = 0; j < arr.length; j++) {
        if (arr[i] == arr[j] && i != j) break;
        else if (j == arr.length - 1){
          uniqArr.push(arr[i])
        } 
      }
    }

    console.log(uniqArr)
Hemanta
  • 11
  • 1
0

this ES6 code worked for me :

a.map(c=>a.filter(b=>c==b)).filter(e=>e.length<2).reduce((total, cur)=> total.concat(cur), [])

Ali Awais
  • 31
  • 2
0

Here is a working method with loops.

  var arr = [-1,2,5,6,2,9,-1,6,5,-1,3];
  var len = arr.length;
  const result = arr
        .filter(value=>{
              var count=0;
              for(var i=0;i<len;i++)
              {
                  if(arr[i]===value)
                    count++;
              }
              return count===1;
          })
  console.log(result);
krishnakirit04
  • 106
  • 1
  • 9
0

const sampleArr = [-1, 2, 5, 6, 2, 9, -1, 6, 5, -1, 3];

function getUnique(arr){
  const result=[]
  const obj={}
  for(let i=0;i<arr.length;i++){
    if(!obj[arr[i]]){
      obj[arr[i]]=true
      result.push(arr[i])
    }else{
      const index= result.indexOf(arr[i])
      if(index!==-1){
        result.splice(result.indexOf(arr[i]),1)
      }
    }
  }
  return result
}

const uniqueArr= getUnique(sampleArr)
console.log(uniqueArr)
0

Here is the solution..

var x = [1,1,2,3,2,4]
var res = []
x.map(d => {
  if(res.includes(d)) {
    // remove value from array
    res = res.filter((a) => a!=d)
  } else {
    // add value to array
    res.push(d)
  }
})
console.log(res) // [3,4]
Ramkumar G
  • 415
  • 1
  • 8
0
//without using any filter also with minimum complexity 
  

const array = [1 , 2, 3, 4, 2, 3, 1, 6, 8,1,1 ];
const unique = new Set(); 
const repetedTreses = new Set();
for(let i=0; i<array.length; i++) {
    if(!unique.has(array[i]) && !repetedTreses.has(array[i])){
        unique.add(array[i]);
    }else{
        repetedTreses.add(array[i]);
        unique.delete(array[i]);
    }
}
let uniqueElements=[...unique];
console.log(uniqueElements);

   
0

var arr = [1, 2, 4, 5, 6, 3, 6, 4];

const getNonDuplicatedValues = () => {
  let nondup = [];
  arr.forEach((e) => {
    if (nondup.includes(e)) {
      let index = nondup.indexOf(e);
      nondup.splice(index, 1);
    } else {
      nondup.push(e);
    }
  });
  return nondup;
};

const Nondup = getNonDuplicatedValues();

console.log("Nondup", Nondup);
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 03 '23 at 10:49
-1

You can use filter and indexOf for that:

console.log(
  [-1, 2, 5, 6, 2, 9, -1, 6, 5, -1, 3].filter((v, i, a) => a.indexOf(v, i + 1) === -1 )
);
ZER0
  • 24,846
  • 5
  • 51
  • 54