Joshua Folorunsho
Joshua Folorunsho

Reputation: 365

How to write a function returning arguments in order in JavaScript?

How can I implement a function which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements?

For example:

1. uniqueInOrder('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
2. uniqueInOrder('ABBCcAD')         == ['A', 'B', 'C', 'c', 'A', 'D']
3. uniqueInOrder([1,2,2,3,3])       == [1,2,3]

Upvotes: 2

Views: 978

Answers (3)

Jagdish Idhate
Jagdish Idhate

Reputation: 7742

You an use .reduce from Array

function uniqueInOrder(data) {
  var test = Array.from(data)
  // Check for previous item, if not the current one then insert
  return test.reduce((res, x, index) => {
    if (res[res.length - 1] !== test[index]) {
      res.push(x)
    }

    return res;

  }, [])
}

console.log(uniqueInOrder('AAAABBBCCDAABBB')); // ['A', 'B', 'C', 'D', 'A', 'B']
console.log(uniqueInOrder('ABBCcAD')); // ['A', 'B', 'C', 'c', 'A', 'D']
console.log(uniqueInOrder([1, 2, 2, 3, 3])); // [1, 2, 3]

Upvotes: 0

stewartmcgown
stewartmcgown

Reputation: 526

The spread operator allows you to accept a sequence of arguments. It makes the sequence of arguments available to the function as an array, which you can then operate on to remove duplicates.

function unique(...items) {
  console.log(items.length)
}

If you are insisting on accepting a string, or an array-like object as the argument, then you can use a set to keep a track of duplicates.

function unique(input) {
  items = new Set()
  for (let item of input) {
     items.add(item)
  }
  return items
}

Those tips should help you answer your question. As for a completed solution, you might need to just use a for loop and check manually:

function unique(input) {
    let output = []
    for (let i = 0; i < input.length; i++) {
        if (input[i] != output[output.length - 1] || i == 0) {
            output.push(input[i])
        }   
    }
    return output
}

> unique("11223332233")
["1", "2", "3", "2", "3"]

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386680

You could take an array from the given data, if an array is given, take that array, if a string is given, take the characters and filter the array by checking the last a and the actual element b and return unequal elements.

const uniqueInOrder = v => Array.from(v).filter((b, i, { [i - 1]: a }) => a !== b);

console.log(uniqueInOrder('AAAABBBCCDAABBB')); // ['A', 'B', 'C', 'D', 'A', 'B']
console.log(uniqueInOrder('ABBCcAD')); // ['A', 'B', 'C', 'c', 'A', 'D']
console.log(uniqueInOrder([1, 2, 2, 3, 3])); // [1, 2, 3]
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Related Questions