4

I have a question in Javascript.

This is the following Array: [1,0,0,0,0,0,0]

I would like to return the only value that does not repeat, that is, 1.

Any suggestions?

I have this:

var result = arr.filter(x => arr.indexOf(x) !== 0);
Marcio
  • 1,685
  • 3
  • 24
  • 39

1 Answers1

16

Using indexOf and lastIndexOf

You can compare indexOf and lastIndexOf and filter()

let arr = [1,0,0,0,0,0,0];
let res = arr.filter(x => arr.indexOf(x) === arr.lastIndexOf(x));

console.log(res)

If you only want the first element you can use find()

let arr = [1,0,0,0,0,0,0];
let res = arr.find(x => arr.indexOf(x) === arr.lastIndexOf(x));

console.log(res)

You can remove duplicates using Set() and then use filter() on it.

let arr = [1,0,0,0,0,0,0];
let res = [...new Set(arr)].filter(x => arr.indexOf(x) === arr.lastIndexOf(x));

console.log(res)

Using nested filter()

let arr = [1,0,0,0,0,0,0];
let res = arr.filter(x => arr.filter(a => a === x).length === 1);
console.log(res)

Using Object and reduce()

This one is best regarding time complexity.

let arr = [1,0,0,0,0,0,0];
let obj = arr.reduce((ac,a) => (ac[a] = ac[a] + 1 || 1,ac),{});
let res = Object.keys(obj).filter(x => obj[x] === 1).map(x => +x || x);

console.log(res)
Community
  • 1
  • 1
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73