JS Search in object array by using array [duplicate] - javascript

This question already has answers here:
Filter array of objects based on another array in javascript
(10 answers)
Closed 3 years ago.
I want to remove all the object from a data array that contains the same id in an array of id. How can I achieve this task without looping it?
const id = [1, 2];
const data = [
{id: 1},
{id: 2},
{id: 3}
];
console.log(data);

You can try with Array.prototype.filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
and Array.prototype.includes():
The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
const id = [1, 2];
const data = [
{id: 1},
{id: 2},
{id: 3}
];
var res = data.filter(i => !id.includes(i.id));
console.log(res);

let newData = data.filter(item => !id.includes(item.id));
console.log(newData);

You can use .filter() and .includes() for filtering your object.
const id = [1, 2];
let data = [
{id: 1},
{id: 2},
{id: 3}
];
data = data.filter((item) => (!id.includes(item.id)));
console.log(data);

You can use method uniqBy from lodash https://lodash.com/docs/4.17.11#uniqBy
const uniqArray = _.uniqBy([{ 'id': 1 }, { 'id': 2 }, { 'id': 1 }], 'id');
console.log(uniqArray)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

Related

Check element presence in array in another array

I have following :
const arr1 = [{id: 1},{id: 2}]
const arr2 = [{id: 1},{id: 4},{id: 3}]
I want to check if elements in arr2 exists in arr1 or vice versa. I want to check for each element in array.
Desired output :
true
false
false
Usually it shouls give error , because one arrays length is longer than first , for the rest I want to get false
O(N) solution with set
const arr1 = [{id: 1},{id: 2}]
const arr2 = [{id: 1},{id: 4},{id: 3}]
const set = new Set()
arr1.forEach((a) => set.add(a.id))
arr2.forEach((b) => {
if (set.has(b.id)) {
console.log("arr1 and arr2 both share"+ b.id)
}
})
You can use array#map with array#some to check if object id in arr2 exist in arr1.
const arr1 = [{id: 1},{id: 2}],
arr2 = [{id: 1},{id: 4},{id: 3}],
result = arr2.map(({id}) => arr1.some(o => id === o.id));
console.log(result);
const arr1 = [{
id: 1
}, {
id: 2
}]
const arr2 = [{
id: 1
}, {
id: 4
}, {
id: 3
}]
let arr1id = arr1.map(i => i.id);
let result = arr2.map(a => arr1id.includes(a.id));
console.log(result);
use hashmap & use below 2 methods of map in java
boolean containsKey(Object key)
V get(Object key)
V get(Object key) to get the object that contains the value associated with the key from map1.
boolean containsKey(Object key) This method returns true if some key equal to the key exists within the map, else return false [ check it in map2]

Remove items from array based on array of values [duplicate]

This question already has answers here:
How to filter an array from all elements of another array
(24 answers)
Closed 2 years ago.
I can't seem to find a solution to this, how do you remove items from an array based on an array of values? The same way you remove one?
const [items, setItems] = useState([
{id: 1, name: "foo"},
{id: 2, name: "bar"},
{id: 3, name: "baz"}
])
I need to remove some ids:
const idsToRemove = [1,3]
// I thought I'd loop
idsToRemove.map(i => items.filter(item => item.id !== i))
This will return an array and something does not feel right at all. If it was to remove one item then that would be ok but removing items from array by an array of ids I not know where to start.
In the loop, I tried to use delete but "undefinded" is in the array: [undefined]:
idsToRemove.map(i => items.map(item => delete item.id === i))
So far React says you cannot update state during a loop. Based on idsToRemove, how can I end up with one item in the state?
You need to put the filter call outside:
items.filter(item => !idsToRemove.includes(item.id))
You can use filter with includes.
items = items.filter(({id})=>!idsToRemove.includes(id));
let items = [
{id: 1, name: "foo"},
{id: 2, name: "bar"},
{id: 3, name: "baz"}
];
const idsToRemove = [1,3]
items = items.filter(({id})=>!idsToRemove.includes(id));
console.log(items);
const items = [
{id: 1, name: "foo"},
{id: 2, name: "bar"},
{id: 3, name: "baz"}
];
const idsToRemove = [1, 3];
console.log(
items.filter(({ id }) => !idsToRemove.includes(id))
);
const [items, setItems] = useState([
{id: 1, name: "foo"},
{id: 2, name: "bar"},
{id: 3, name: "baz"}
]
const idsToRemove = [1,3]
setItems(items.filter((item)=> !idsToRemove.includes(item.id)))
using functional programming you won't be changing the current state obj but creating a new one, hence maintaining the sanity of React immutability.

How to filter an array with RxJS operator

Hello to every one i am new to RxJs and reactive programming i would like to filter an array like this:
let subscription = Rx.Observable.from([{id: 1}, {id: 2}, {id: 3}],[{id: 4}, {id: 5}, {id: 6}]);
if i have one array a i can do this:
let subscription = Rx.Observable.from([{id: 1}, {id: 2}, {id: 3}]);
subscription.filter(x => x.id === 1).subscribe(x => console.log(x));
But how i can to do with the second array?
If you know you'll always have array of arrays you can flatten the array and then run filter:
const o = Rx.Observable.of([{id: 1}, {id: 2}, {id: 3}],[{id: 1}, {id: 2}, {id: 3}])
.concatMap(array => array) // flatten the array into single emissions
.filter(x => x.id === 1)
.subscribe(x => console.log(x));
I'm using .of that accepts multiple arguments. However it takes them as they are unlike the from method that iterates the array.
There are a couple of solutions. The easy way is just to create the right observable.
You could directly create the right observable by concatenating the array in your input of from:
let subscription = Rx.Observable.from([{id: 1}, {id: 3}].concat([{id: 1}]));
You could use Rx.Observable.of which directly takes as many arguments as value in the created Observable and use the spread operator:
let subscription = Rx.Observable.of(...[{id: 1}, {id: 3}].concat(...[{id: 1}]));
You could also merge two different observables:
let subscription = Rx.Observable.from([{id: 1}
.merge(Rx.Observable.from([{ id: 1}]);
There are possibly other solutions that could work like using an array of array and then flatMapping the array.

Lodash Remove objects from array by matching ids array

I have an array of objects like:
var a = [
{id: 1, name: 'A'},
{id: 2, name: 'B'},
{id: 3, name: 'C'},
{id: 4, name: 'D'}
];
And Ids array which i want to remove from array a :
var removeItem = [1,2];
I want to remove objects from array a by matching its ids, which removeItem array contains. How can i implement with lodash.
I Checked lodash's _.remove method, but this need a specific condition to remove an item from array. But i have list of ids which i want to remove.
As you mentioned you need the _.remove method and the specific condition you mention is whether the removeItem array contains the id of the checked element of the array.
var removeElements = _.remove(a, obj => removeItem.includes(obj.id));
// you only need to assign the result if you want to do something with the removed elements.
// the a variable now holds the remaining array
You have to pass a predicate function to .remove method from lodash.
var final = _.remove(a, obj => removeItem.indexOf(obj.id) > -1);
using indexOf method.
The indexOf() method returns the first index at which a given element
can be found in the array, or -1 if it is not present.
You can do it using native javascript using filter method which accepts as parameter a callback function.
var a = [
{id: 1, name: 'A'},
{id: 2, name: 'B'},
{id: 3, name: 'C'},
{id: 4, name: 'D'}
];
var removeItem = [1,2];
a = a.filter(function(item){
return removeItem.indexOf( item.id ) == -1;
});
console.log(a);
But filter method just creates a new array by applying a callback function.
From documentation:
The filter() method creates a new array with all elements that pass
the test implemented by the provided function.
If you want to modify the original array use splice method.
var a = [
{id: 1, name: 'A'},
{id: 2, name: 'B'},
{id: 3, name: 'C'},
{id: 4, name: 'D'}
];
var removeItem = [1,2];
removeItem.forEach(function(id){
var itemIndex = a.findIndex(i => i.id == id);
a.splice(itemIndex,1);
});
console.log(a);

how to prevent sequence when i use Array.forEach [duplicate]

This question already has answers here:
Sort JavaScript object by key
(37 answers)
Closed 6 years ago.
const a = {};
array.forEach(item => {
a[item.id] = item;
})
when i get a, I found it was sort by item.id. How to prevent the sort when forEach.
if array = [{id: 2}, {id: 6}, {id : 1}], and then I get a = {1: {id: 1}, 2: {id: 2}, 6: {id: 6}}.
my want is a={2: {id: 2}, 6: {id:6}, 1: {id: 1}}
I don't think you can enforce a particular object key sequence in JS. You can, however, create an array of the keys.
const a = {};
const originalSequence = [];
array.forEach(item => {
a[item.id] = item;
originalSequence.push(item.id);
})

Categories