14

I'm trying to strip the duplicate array values from my current array. And I'd like to store the fresh list (list without duplicates) into a new variable.

var names = ["Daniel","Lucas","Gwen","Henry","Jasper","Lucas","Daniel"];

const uniqueNames = [];
const namesArr = names.filter((val, id) => {
    names.indexOf(val) == id;  // this just returns true
});

How can I remove the duplicated names and place the non-duplicates into a new variable?

ie: uniqueNames would return...

["Daniel","Lucas","Gwen","Henry","Jasper"] 

(I'm using react jsx) Thank you!

5
  • Somebody upvoted my original answer, which I deleted because I didn't fully understand the question (and it was probably wrong anyway). The meat of it was that you're missing a return inside your filter! Commented May 13, 2016 at 19:35
  • @ScottKaye why do you think your solution is wrong..? Commented May 13, 2016 at 19:38
  • @WildWidow I wasn't sure if he wanted the array to contain the removed elements, or the array after those elements were removed. Commented May 13, 2016 at 19:41
  • @ScottKaye the array after the duplicates were removed :) sorry should have specified Commented May 13, 2016 at 19:42
  • 1
    @ScottKaye when I was typing my solution, I think I glimpsed at your solution just before I submit mine, I believe you had the answer for bot h removed elements and the existing elements which is correct :) Commented May 13, 2016 at 19:43

6 Answers 6

42

You can do it in a one-liner

const uniqueNames = Array.from(new Set(names));

// it will return a collection of unique items

Note that @Wild Widow pointed out one of your mistake - you did not use the return statement. (it sucks when we forget, but it happens!)

I will add to that that you code could be simplified and the callback could be more reusable if you take into account the third argument of the filter(a,b,c) function - where c is the array being traversed. With that said you could refactor your code as follow:

const uniqueNames = names.filter((val, id, array) => {
   return array.indexOf(val) == id;  
});

Also, you won't even need a return statement if you use es6

const uniqueNames = names.filter((val,id,array) => array.indexOf(val) == id);
Sign up to request clarification or add additional context in comments.

Comments

5

If you want to remove duplicate values which contains same "id", You can use this.

const arr = [
  { id: 2, name: "sumit" },
  { id: 1, name: "amit" },
  { id: 3, name: "rahul" },
  { id: 4, name: "jay" },
  { id: 2, name: "ra one" },
  { id: 3, name: "alex" },
  { id: 1, name: "devid" },
  { id: 7, name: "sam" },
  ];

function getUnique(arr, index) {

  const unique = arr
       .map(e => e[index])

       // store the keys of the unique objects
       .map((e, i, final) => final.indexOf(e) === i && i)
  
       // eliminate the dead keys & store unique objects
      .filter(e => arr[e]).map(e => arr[e]);      

   return unique;
}

console.log(getUnique(arr,'id'))

Result :

[ 
  { id: 2, name: "sumit" },
  { id: 1, name: "amit" },
  { id: 3, name: "rahul" },  
  { id: 4, name: "jay" },  
  { id: 7, name: "sam" }
]

1 Comment

Since I found this code very confusing, I posted the refactored version as a separate answer.
2

you forgot to use return statement in the filter call

const namesArr = duplicatesArray.filter(function(elem, pos) {
    return duplicatesArray.indexOf(elem) == pos;
}); 

Comments

1

Since I found the code of @Infaz 's answer used somewhere and it confused me greatly, I thought I would share the refactored function.

function getUnique(array, key) {
  if (typeof key !== 'function') {
    const property = key;
    key = function(item) { return item[property]; };
  }
  return Array.from(array.reduce(function(map, item) {
    const k = key(item);
    if (!map.has(k)) map.set(k, item);
    return map;
  }, new Map()).values());
}

// Example
const items = [
  { id: 2, name: "sumit" },
  { id: 1, name: "amit" },
  { id: 3, name: "rahul" },
  { id: 4, name: "jay" },
  { id: 2, name: "ra one" },
  { id: 3, name: "alex" },
  { id: 1, name: "devid" },
  { id: 7, name: "sam" },
];
console.log(getUnique(items, 'id'));
/*Output:
[ 
  { id: 2, name: "sumit" },
  { id: 1, name: "amit" },
  { id: 3, name: "rahul" },  
  { id: 4, name: "jay" },  
  { id: 7, name: "sam" }
]
*/

Comments

1

Also you can do this

{Array.from(new Set(yourArray.map((j) => j.location))).map((location) => (
          <option value={`${location}`}>{location}</option>
        ))}

Comments

0

Here is the code you can do:

interface Row {
    id: number;
    deviceId: string;
}

function filterUniqueDevices(rows: Row[]): Row[] {
    const uniqueDevices = new Set<string>(); // Use Set to keep track of unique device ids
    const filteredRows: Row[] = [];

    for (const row of rows) {
        if (!uniqueDevices.has(row.deviceId)) {
            //If the device id is not present, add it to the Set and add it to the resulting array
            uniqueDevices.add(row.deviceId);
            filteredRows.push(row);
        }
    }

    return filteredRows;
}

// Example:

const rows: Row[] = [
    { id: 1, deviceId: 'iddevice A' },
    { id: 2, deviceId: 'iddevice A' },
    { id: 3, deviceId: 'iddevice A' },
    { id: 4, deviceId: 'iddevice B' },
    { id: 5, deviceId: 'iddevice C' },
    { id: 6, deviceId: 'iddevice D' }
];


const uniqueRows = filterUniqueDevices(rows);

console.log(uniqueRows);

//OUT PUT

[
    { id: 1, deviceId: 'iddevice A' },
    { id: 4, deviceId: 'iddevice B' },
    { id: 5, deviceId: 'iddevice C' },
    { id: 6, deviceId: 'iddevice D' }
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.