-2

I have an array of json objects:

[ {id:0, name:'A'}, {id:1, name:'B'}...{id:n, name:'N'} ]

How do i get the value (name) base on a given id, without iterating the array? Perhaps using map or some filter method...

0x75aaa
  • 45
  • 6

5 Answers5

2

const arr = [ {id:0, name:'A'}, {id:1, name:'B'},{id:3, name:'N'} ];
const inputId = 1;

const foundObj = arr.find(({ id }) => id === inputId);
if (foundObj) console.log(foundObj.name);

This still does iterate the array internally, though (as any method will).

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

This find method will find object based on your object property and value.

ArrayName.find(x => x.id === 0);
1

let array = [ {id:0, name:'A'}, {id:1, name:'B'}, {id:'n', name:'N'} ]
//To search in array we must iterate. But if you want to optimise performance for multiple searches you can map it to object by id.

let map = array.reduce((acc,element)=>{acc[element.id]=element;return acc;},{})

console.log(map[0])
console.log(map[1])
console.log(map.n) //As n was used as id.
amitdigga
  • 6,550
  • 4
  • 26
  • 31
1

When you want to find an element in a collection, array might not be the best choice, objects or maps are much better in that case.

Each time you have to find an element, you would have to iterate over the array which would take O(n) time.

To avoid this, you could have an API layer in the middle, to convert your array into an a data structure which maps values by unique keys. You could achieve this by a plain Javascript Object.

That way you could find your element by id in O(1) without any iteration.

//original data
let arr = [ {id:0, name:'A'}, {id:1, name:'B'}, {id:2, name:'N'} ];

//convert it into object
let obj = arr.reduce((acc, curr) => {
    acc[curr.id] = curr;
    return acc;
}, {});

//modified data
{ 0: { id: 0, name: 'A' },
  1: { id: 1, name: 'B' },
  2: { id: 2, name: 'N' } }

//Now, you can look up value on any id as 
obj[id].name;
Jatin Gupta
  • 889
  • 6
  • 15
1

Maps take one iteration to construct. Value retrieval thereon is sublinear.

// Input.
const input = [{id: 0, name:'A'}, {id: 1, name:'B'}, {id: 13, name:'N'}]

// To Map.
const toMap = (A) => new Map(A.map(x => [x.id, x]))

// Output.
const output = toMap(input)

// Proof.
console.log(output.get(0))
console.log(output.get(1))
console.log(output.get(13))
Arman Charan
  • 5,669
  • 2
  • 22
  • 32