-2

I want to filter an array of objects using an array but I want the results on the basis of array index and the result should be repeated when the array index value is repeated.

const data = [{
    id='1',
    name:'x'
},
{
    id='4',
    name:'a'
},
{
    id='2',
    name:'y'
},
{
    id='3',
    name:'z'
}

]

cons idArray = [1,4,3,2,4,3,2]

I have tried following code and get the result only once

const filteredData = data.filter(arrayofObj => idArray.includes(arrayofObj.id))
  console.log(filteredData)

expected output is expected output is =

[{id = '1,name:'x'},{id='4',name:'a'},{
    id='3',
    name:'z'
},
{
    id='2',
    name:'y'
},{
    id='4',
    name:'a'
},
{
    id='3',
    name:'z'
},{
    id='2',
    name:'y'
}]
1
  • 3
    You are not going to be able to filter an array of 4 items and get an array of 7 items. Filter removes items. Maybe you should start with map() on your idArray instead. Commented Jan 31, 2020 at 7:35

2 Answers 2

0

First convert data array into Object with id's as keys. Second, use map method over idArray and gather objects from above object.

const data = [
  {
    id: "1",
    name: "x"
  },
  {
    id: "4",
    name: "a"
  },
  {
    id: "2",
    name: "y"
  },
  {
    id: "3",
    name: "z"
  }
];

const dataObj = data.reduce((acc, curr) => {
  acc[curr.id] = { ...curr };
  return acc;
}, {});

const idArray = [1, 4, 3, 2, 4, 3, 2];

const results = idArray.map(id => ({ ...dataObj[id] }));

console.log(results);

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

Comments

0

You could map with a Map.

const
    data = [{ id: '1', name: 'x' }, { id: '4', name: 'a' }, { id: '2', name: 'y' }, { id: '3', name: 'z' }],
    idArray = [1, 4, 3, 2, 4, 3, 2],
    result = idArray.map(Map.prototype.get, new Map(data.map(o => [+o.id, o])));

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.