1

I would like to have a "unique" array of another multi-dimensional array, the array looks something like this:

var bigArray = Array(
                ["text", "text", "A", 1, 2],
                ["text", "text", "S", 3, 4],
                ["text", "text", "S", 4, 4],
                ["text", "text", "S", 5, 7],
                ["text", "text", "S", 2, 1],
                ["text", "text", "S", 1, 0]
            );

The result should be something like

uniqueArray = [A, S]

And this is the filter function I have atm:

var uniqueArray = bigArray.filter(function(item, i, ar){ return ar.indexOf(item) === i; });

The function gives me ALL the unique values in the big array, but I only need the unique values from row[2]. I guess the parameters must be tweaked a bit from the filter function but I don't understand them well. Thanks for your help

0

2 Answers 2

4

Array#filter returns items if the array and not parts of the inner array. Therefore, you need a different approach, by mapping only the wanted value and fillter later.

With ES6 you could map the wanted column and use Set for unique values.

var bigArray = [["text", "text", "A", 1, 2], ["text", "text", "S", 3, 4], ["text", "text", "S", 4, 4], ["text", "text", "S", 5, 7], ["text", "text", "S", 2, 1], ["text", "text", "S", 1, 0]],
    result = [...new Set(bigArray.map(a => a[2]))];
    
console.log(result);

ES5 with a hash table.

var bigArray = [["text", "text", "A", 1, 2], ["text", "text", "S", 3, 4], ["text", "text", "S", 4, 4], ["text", "text", "S", 5, 7], ["text", "text", "S", 2, 1], ["text", "text", "S", 1, 0]],
    hash = Object.create(null),
    result;

bigArray.forEach(function (a) {
    hash[a[2]] = true;
});
result = Object.keys(hash);
    
console.log(result);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Nina for your answer, but it's too complex for me I'm sorry :p I will go for the answer here below from @brk it's more readable and I understand what it does. Thanks for your time anyway.
1

You can do like this

var bigArray = Array(
  ["text", "text", "A", 1, 2],
  ["text", "text", "S", 3, 4],
  ["text", "text", "S", 4, 4],
  ["text", "text", "S", 5, 7],
  ["text", "text", "S", 2, 1],
  ["text", "text", "S", 1, 0]
);

var newArray = []
bigArray.forEach(function(item) {
  if (newArray.indexOf(item[2]) == -1) {
    newArray.push(item[2])
  }
})
console.log(newArray)

DEMO

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.