Reputation: 400
Problem Statement:- arr1 is an ordered array with values 3,4 and 5.In the list shown below all the objects whose property "c" matches with that of the elements of the array should be updated with index +1 of the found index at arr1.
I have two different ways of achieving the same, which one has a better time complexity and which one should be chosen?
var arr1 = [3,4,5];
var list = [{a:1,b:2,c:3},{a:1,b:2,c:3},{a:2,b:3,c:5},{a:3,b:4,c:4}];
output: [{a:1,b:2,c:1},{a:1,b:2,c:1},{a:2,b:3,c:3},{a:3,b:4,c:3}];
1: Find the index and then update the index:
list.forEach((obj) => {
var i = arr1.indexOf(obj.c);
if(i > -1) {
obj.c = i +1;
}
});
arr1.forEach((id,index) => {
list.forEach((obj) => {
if(obj.c === id){
obj.c = index+1;
}
})
});
Which is the better way to write and why?
Upvotes: 1
Views: 203
Reputation: 386868
You could take a Map
with value and index in advance, with a single loop.
And another loop for all elements of list
, where c
gets an update if necessary.
An instance of Map
is a data structure to keep a key value relation with a fast access O(1) to the value.
var array = [3, 4, 5],
list = [{ a: 1, b: 2, c: 3 }, { a: 1, b: 2, c: 3 }, { a: 2, b: 3, c: 5 }, { a: 3, b: 4, c: 4 }],
values = new Map;
array.forEach(Map.prototype.set, values);
list.forEach(o => {
if (values.has(o.c)) o.c = values.get(o.c) + 1;
});
console.log(list);
Upvotes: 2