skip to Main Content

How to remove the duplicate strings in an array. I tried this which doesn’t workout.

var input = ['john','john','rio','ravi','josva','ravi'];

    let remove = function(){
    let result = [];
    for (let i = 0; i<input.length; i++){
        if(input[i] == input[i]){
            return false;
        }else{
            return true;
        }
    }
    result.push(input[i]);
    console.log(result);
    };
remove();

3

Answers


  1. var input = ["john", "john", "rio", "ravi", "josva", "ravi"];
    var uniqueItems = input.filter((item, index, self) => {
     // returns -1 if it's not found
     return self.indexOf(item) === index; 
    });
    console.log(uniqueItems);
    Login or Signup to reply.
  2. You can use this code:

    var input = ['john','john','rio','ravi','josva','ravi'];
    var output = input.filter (function (item, index, array) {
      return array.indexOf (item) == index;
    });
    console.log (output); // ['john','rio','ravi','josva']
    Login or Signup to reply.
  3. let input = ['john','john','rio','ravi','josva','ravi'];
    
    let remove = function(){
        let result = [];
        for (let i = 0; i < input.length; i++){
            if (result.indexOf(input[i]) === -1) {
                result.push(input[i]);
            }
        }
        return result;
    };
    

    You can do it this way also

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search