Hayk Safaryan Hayk Safaryan - 1 month ago 7
Javascript Question

JS Getting a new array with just the elements that contain certain value

So I have this array

"myArray": [
{
'specialValue' : 111,
// other values,arrays,objects and so on
},
{
'specialValue' : 555,
// other values,arrays,objects and so on
},
{
'specialValue' : 111,
// other values,arrays,objects and so on
},
{
'specialValue' : 555,
// other values,arrays,objects and so on
},
]


I want to make a new array that contains only those objects (with all their properties) that have same
specialValue

Please help me to do it with js

EDIT: The specialValue is not know beforehand. I just give this array as a structure example.

Answer

You could group it with a hash table.

var object = { "myArray": [{ 'specialValue': 111, propA: true }, { 'specialValue': 555, propC: true }, { 'specialValue': 111, propB: true }, { 'specialValue': 555, propD: true }, ] },
    grouped = object.myArray.reduce(function (hash) {
        return function (r, a) {
            if (!hash[a.specialValue]) {
                hash[a.specialValue] = [];
                r.push(hash[a.specialValue]);
            }
            hash[a.specialValue].push(a);
            return r;
        };
    }(Object.create(null)), []);

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

ES6 with Map

var object = { "myArray": [{ 'specialValue': 111, propA: true }, { 'specialValue': 555, propC: true }, { 'specialValue': 111, propB: true }, { 'specialValue': 555, propD: true }, ] },
    grouped = object.myArray.reduce((map =>
        (r, a) =>
           (!map.has(a.specialValue) && map.set(a.specialValue, r[r.push([]) - 1]), map.get(a.specialValue).push(a), r))(new Map), []);

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }