最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove duplicate elements from an unsorted array without using any inbuilt function or without using any other arra

programmeradmin0浏览0评论

Hi in my first nodejs interview interviewer ask me to remove all duplicate elements from an unsorted array without using any inbuilt function using java script in minimum TC and without using any other array.

This is my efforts.

 var input = [1, 2, 3, 3, 4, 5,2, 6,3,6,1];
var current = input[0];
var found = false;
function removeDuplicate() {
    for (var i = 0; i < input.length; i++) {
        if (current == input[i]) {
            //found = false;
        } else if (current != input[i]) {
            console.log(" " + current);
            current = input[i];
            found = false;
        }
    }
    console.log(" " + current);

}
removeDuplicate();

Hi in my first nodejs interview interviewer ask me to remove all duplicate elements from an unsorted array without using any inbuilt function using java script in minimum TC and without using any other array.

This is my efforts.

 var input = [1, 2, 3, 3, 4, 5,2, 6,3,6,1];
var current = input[0];
var found = false;
function removeDuplicate() {
    for (var i = 0; i < input.length; i++) {
        if (current == input[i]) {
            //found = false;
        } else if (current != input[i]) {
            console.log(" " + current);
            current = input[i];
            found = false;
        }
    }
    console.log(" " + current);

}
removeDuplicate();

Share Improve this question asked Jul 19, 2017 at 8:58 Manish chauhanManish chauhan 651 gold badge2 silver badges10 bronze badges 4
  • Is this a question? if so, what's the question? – StudioTime Commented Jul 19, 2017 at 9:00
  • Can't be done. You have to use splice, slice or something similar to modify the array in place, and you have to use indexOf, lastIndexOf or includes to check for dupes, and thet are all native inbuilt array methods. – adeneo Commented Jul 19, 2017 at 9:01
  • 1 @adeneo dont you think that splice, slice or whatever have been made using pure javascript? So i m pretty sure it can be done without using it – kikiwie Commented Jul 19, 2017 at 9:05
  • No, those methods are written in C++ or whatever the engine is written in. Not all built-ins can be replicated in JS, escpecially when you can't use other built in methods to do so. – adeneo Commented Jul 19, 2017 at 9:32
Add a ment  | 

5 Answers 5

Reset to default 4

I don't really understand precisely what inbuild functions are or to what extent is a function inbuilt, so I'm assuming I'm not allowed to use indexOf, hasOwnProperty, Array.prototype.push, ...

const input = [1, 2, 3, 3, 4, 5,2, 6,3,6,1];

function removeDuplicate(arr) {
    const result = [];
    let idx = 0;
    const tmp = {};

    for (let i = 0; i < arr.length; i++) {
        if (!tmp[arr[i]]) {
            tmp[arr[i]] = 1;
            result[idx] = arr[i];
            idx++;
        } 
    }
    return result;
}

console.log(removeDuplicate(input));

If you want to remove the elements in place, then the best I can do is save the elements in place, and give the length of the eventual array. But in JavaScript, it's actually valid since arrays in JavaScript are just objects that are enumberable with an extra property length.

const input1 = [1, 2, 3, 3, 4, 5,2, 6,3,6,1];
const input2 = [1, 2, 3, 3, 4, 5,2, 6,3,6,7];

function removeDuplicate(arr) {
    let length = 0;
    const tmp = {};

    for (let i = 0; i < arr.length; i++) {
        if (!tmp[arr[i]]) {
            tmp[arr[i]] = 1;
            arr[length] = arr[i];
            length++;
        }
    }
    
    // the last element is not a duplicate
    if (!tmp[arr[arr.length-1]]) {
        length--;
    }
    arr.length = length;
    return arr;
}

console.log(removeDuplicate(input1));
console.log(removeDuplicate(input2));

One line of vanilla JavaScript with no loops

Since this seems like a homework then at least make some effort to make the solution interesting.

This is my first solution but it uses a built-in .filter() method:

const removeDuplicate = (c=>a=>a.filter(e=>!(c[e]||(c[e]=1)&&0)))({});

Here is another solution without using built-ins:

const f = (c=>(h,...r)=>h?(c[h]|=0)||c[h]++?f(...r):[h,...f(...r)]:[])({});
const removeDuplicate = a => f(...a);

Here you go. One line of vanilla JavaScript plus a convenience wrapper- the second line is so you can use:

console.log(removeDuplicate(input));
// or with literals:
console.log(removeDuplicate([1, 2, 3, 3, 4, 5, 2, 6, 3, 6, 1]));

but if you're fine with this:

console.log(f(...input));
// or with literals:
console.log(f(1, 2, 3, 3, 4, 5, 2, 6, 3, 6, 1));

then you can remove the second line (and of course rename f to something better).

var arr=[
{id: 1, "name": "kumar"}, 
{id: 1, "name": "kumar"}, 
{id: 2, "name": "kumar1"}, 
{id: 2, "name": "kumar1"}, 
{id: 3, "name": "kumar2"}
];
var res=[];
var count={};
arr.forEach((el,ind)=>{
   count[el.id]=(count[el.id] || 0)+1;
   if(count[el.id]<2){
        res.push(el);
   }
})
 console.log(res)//[{ id: 1, name: 'kumar' },{ id: 2, name: 'kumar1' },{ id: 3, name: 'kumar2' }]enter code here

let arrayB = [
   {id: 1, name: "abc"}, 
   {id:2, name: "abccc"},
   {id: 2, name: "xyz"}, 
   {id:3, name: "abccc"},
   {id: 4, name : "asdada"}
  ];

function findRepeatedObject(arr) {
  var newObj = {};
  var newArr = [];
  for (i = 0; i < arr.length; i++) {
    if (newObj[arr[i].id]) {
      newObj[arr[i].id] += 1;
    } else {
      newObj[arr[i].id] = 1;
      newArr.push(arr[i])
    }
  }
  return newArr;
}
console.log(findRepeatedObject(arrayB));
//output will be [{ id: 1, name: 'abc' },{ id: 2, name: 'abccc' },{ id: 3, name: 'abccc' },{ id: 4, name: 'asdada' }];

let arr =[1, 2, 3, 3, 4, 5,2, 6,3,6,1];
function removeduplicate(arr) {
  let result = [],k=0,lastoccur;
  for (let i = 0;i<arr.length;i++) {
    for (let j = 0;j<arr.length;j++) {
      if (arr[i] == arr[j]) {
        lastoccur = j 
      }
    }
    if (i === lastoccur) { 
      result[k] = arr[i];
      k++;
    }
  }
  return result;
}
console.log(removeduplicate(arr));

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论