0

I have this question List out all the unique values of attribute “z” found in the following array list: and the input is

var x = ["<r><a z=\"4\"><a z=\"2\"></r>"]

I tried solve it with following code

let x = ["<r><a z=\"4\"><a z=\"2\"></r>"];
let unique = [];
let temp = [];
let pattern = /[0-9]/g;
x.filter((item, i) => {
  temp = item.match(/\d+/g).map(Number);
});

The output should be unique numbers instead i.e. 1,2,3,4 but it gives a long array of random numbers between 1-4. How to fix this?

Om3ga
  • 30,465
  • 43
  • 141
  • 221
  • `unique.map(... unique.push` - each time you loop through the unique elements you push them back on to itself – freedomn-m Apr 21 '20 at 10:52
  • 1
    Sorry, but your usage of `filter` and `map` makes no sense at all. Can you explain how this was supposed to work? (For the usual solutions, see the duplicate) – Bergi Apr 21 '20 at 10:53
  • Can you work on it a little in the answer? – Om3ga Apr 21 '20 at 10:53
  • it is suppose to get unique numbers from attribute `z`. – Om3ga Apr 21 '20 at 10:54
  • *a long array of random numbers* - they're not random at all. `x=[3,2]` output = 3,2 (then extra 2,3). 2nd output is the same 3,2,2,3 + 1,2 – freedomn-m Apr 21 '20 at 10:54
  • 1
    There is no need for `mapping` though the `unique` and `temp` array. Just hold all the values found: `all = unique.concat(temp);` [And filter out all the unique values](https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates) afterwards. – 0stone0 Apr 21 '20 at 10:55
  • That question does not answer my question. – Om3ga Apr 21 '20 at 11:14
  • We can't add an answer if the question is marked as duplicate. Maybe try to reopen it by elaborating the question a bit further? – 0stone0 Apr 21 '20 at 11:19
  • That RegEx is really crude. It's against StackOverflow policy to do your homework for you. Probably seems like you haven't put enough effort in, and your code is kind of all over the place. But ya, you didn't deal with the first array, and your iterations don't make sense. The question you asked specifically about (unique values in an array) was answered in the link. Here's what your code should somewhat look like: `var x = ["",""]; uniq = new Set(x.reduce( (acc,x) => acc.concat(x.match(/\d+/g)), [] ));` – user120242 Apr 22 '20 at 05:53
  • Ah, "long array of random numbers". You didn't give the full input you are working with. Your Regex is too simple and does not properly extract only "z" attributes. That would be a separate question, and your input is not complete enough for anyone to address the problem. – user120242 Apr 22 '20 at 06:09

0 Answers0