'Filter a array in javascript

[{"1":"A"},{"2":"A"},{"3":"B"},{"4":"A"},{"5":"C"},{"6":"B"},{"7":"B"}]

This is a array where first element is id and second is user. I have to filter this array according to user like- If user is 'A' then array will be [1,2,4] If user is 'B' then array will be [3,7]

How to do this in javascript? Do i need to use map or filter method?



Solution 1:[1]

Use Array#filter, String#split and Array#map methods.

var arr = ['1:A', '2:A', '3:B', '4:A', '5:C', '6:B', '7:B'];


// filter out array 
var res = arr.filter(function(v) {
  // split and check user is A
  return v.split(':')[1].trim() == 'A'
}).map(function(v) {
  // retrive the number part and parse 
  return Number(v.split(':')[0]);
});

console.log(res);

Or use single Array#forEach loop.

var arr = ['1:A', '2:A', '3:B', '4:A', '5:C', '6:B', '7:B'];

// initialize array to hold the result
var res = [];

// iterate over the array element
arr.forEach(function(v) {
  // strint the string 
  var spl = v.split(':');
  // check user is A
  if (spl[1].trim() == 'A')
  // if user is A parse and push value to result array
    res.push(Number(spl[0]))
});

console.log(res);

UPDATE : If it's an object then use Object.keys and Array#map methods.

var obj = {
  1: 'A',
  2: 'A',
  3: 'B',
  4: 'A',
  5: 'C',
  6: 'B',
  7: 'B'
};

var res = Object.keys(obj) // get all object keys
  // filter out keys array
  .filter(function(k) {
    // check the property value
    return obj[k] == 'A';
    // parse the result array if you want to convert 
    // into a Number array
  }).map(Number);

console.log(res);

Solution 2:[2]

My idea is, you could try to create a function to filter which user you want. Here is my code example you can try:

let userData = [{"1":"A"},{"2":"A"},{"3":"B"},{"4":"A"},{"5":"C"},{"6":"B"},{"7":"B"}];

function filterByUser(user) {
    let dataResult = [];
    userData.forEach((data) => {
        if (Object.values(data)[0] == user){
            dataResult.push(Object.keys(data)[0]);
        }
    })
    return dataResult;
}

// If user is A will get [1,2,4]
console.log(filterByUser('A'))

// If user is B will get [3,6,7]
console.log(filterByUser('B'));

Solution 3:[3]

You could use Array#reduce and group all items by the user.

var array = ['1:A', '2:A', '3:B', '4:A', '5:C', '6:B', '7:B'],
    groups = array.reduce(function (r, a) {
        var p = a.split(':');
        r[p[1]] = r[p[1]] || [];
        r[p[1]].push(p[0]);
        return r;
    }, Object.create(null));

console.log(groups);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 wildgamer
Solution 3 Nina Scholz