I have this array of customer licenses I am sorting through and creating a live search function with an array that updates properly. The issue I am facing is that I want my filtered array to be an array like this [[{},{},{},{},{}]] currently after typing in a word to filter the array looks like this instead [ [{}], [{},{}], [{},{}] ] or something similar whereas its an array with multiple arrays instead of just one.
I'm sure its something simple that I have overlooked in the past couple of hours trying to figure out how to achieve what I want.
function FilterResults(term, results)
{
return results.reduce((filtered, group) =>
{
const match = group.filter(({ customerName }) => customerName.toLowerCase().includes(term.toLowerCase()));
match.length && filtered.push(match);
return filtered;
}, []);
}
I am not sure if you really want an array inside of another array but
You can do it like this one.
I have spread and then pushed the match array and returned the result in a new array.
function FilterResults(term, results)
{
const res = results.reduce((filtered, group) =>
{
const match = group.filter(({ customerName }) => customerName.toLowerCase().includes(term.toLowerCase()));
match.length && filtered.push(...match);
return filtered;
}, []);
return [res]
}
Related
I have an array of 10 users, I want to filter the users based on the 'intresses' (that means interests in dutch) array within the users. So for example I want to filter all the users that have the interests 'Afrika' (like index 2).
This is what I tried but it will give me an empty array back.
var newArray = gesorteerdeMatchPercentages.filter((el) => {
el.intresses.forEach((item) => {
return item.naam === "Afrika";
});
});
console.log("new", newArray);
If i understand you correctly you could do that using Array.prototype.some() like this
var newArray = gesorteerdeMatchPercentages.filter((el) => {
return el.intresses.some(el => el.naam === 'Afrika');
});
I'm having some issues with filtering 2 arrays of objects. My goal is to filter the main array with another array, both arrays of numbers.
Demo code below
partners?.map((e) => {
let products = e.products.map(a => a.externalProductId)
let porArr: number[] = active.map((a) => a.externalProductId);
if (products.filter(item => porArr.includes(item))) {
return console.log(e)
} else {
return console.log('bad')
}
})
products preview
[
6268,
6267,
9745,
9746
]
porArr preview
[
6267,
6270,
6269,
6641,
9559,
9560,
9660,
9663,
9665
]
for some reason the func still returns always true in the if rule.
Any help greatly welcome!
Since you're not assigning the filtered array anywhere, you don't need to use .filter(). Use .some() to test if any of the array elements satisfy the condition.
if (products.any(product => porArr.includes(product)) {
// do something
}
How do I search an array for any instances of multiple specified string values?
const arrayOfObjects = [{
name: box1,
storage: ['car', 'goat', 'tea']
},
{
name: box2,
storage: ['camel', 'fox', 'tea']
}
];
arrayOfSearchItems = ['goat', 'car', 'oranges'];
If any one or all of the arrayOfSearchItems is present in one of the objects in my array, I want it to either return false or some other way that I can use to excluded that object that is in my arrayOfObjects from a new, filtered arrayOfObjects without any objects that contained the arrayOfSearchItems string values. In this case I would want an array of objects without box1.
Here is what I have tried to do, based on other suggestions. I spent a long time on this. The problem with this function is that it only works on the first arrayOfSearchItems strings, to exclude that object. It will ignore the second or third strings, and not exclude the object, even if it contains those strings. For example, it will exclude an object with 'goat'. Once that happens though, it will no longer exclude based on 'car'. I have tried to adapt my longer code for the purposes of this question, I may have some typos.
const excludeItems = (arrayOfSearchItems, arrayOfObjects) => {
let incrementArray = [];
let userEffects = arrayOfSearchItems;
let objects = arrayOfObjects;
for (i = 0; i < userEffects.length; i++) {
for (x = 0; x < objects.length; x++) {
if (objects[x].storage.indexOf(userEffects) <= -1) {
incrementArray.push(objects[x]);
}
}
}
return(incrementArray);
}
let filteredArray = excludeItems(arrayOfSearchItems, arrayOfObjects);
console.log(filteredArray);
Thanks for providing some example code. That helps.
Let's start with your function, which has a good signature:
const excludeItems = (arrayOfSearchItems, arrayOfObjects) => { ... }
If we describe what this function should do, we would say "it returns a new array of objects which do not contain any of the search items." This gives us a clue about how we should write our code.
Since we will be returning a filtered array of objects, we can start by using the filter method:
return arrayOfObjects.filter(obj => ...)
For each object, we want to make sure that its storage does not contain any of the search items. Another way to word this is "every item in the starage array does NOT appear in the list of search items". Now let's write that code using the every method:
.filter(obj => {
// ensure "every" storage item matches a condition
return obj.storage.every(storageItem => {
// the "condition" is that it is NOT in the array search items
return arrayOfSearchItems.includes(storageItem) === false);
});
});
Putting it all together:
const excludeItems = (arrayOfSearchItems, arrayOfObjects) => {
return arrayOfObjects.filter(obj => {
return obj.storage.every(storageItem => {
return arrayOfSearchItems.includes(storageItem) === false;
});
});
}
Here's a fiddle: https://jsfiddle.net/3p95xzwe/
You can achieve your goal by using some of the built-in Array prototype functions, like filter, some and includes.
const excludeItems = (search, objs) =>
objs.filter(({storage:o}) => !search.some(s => o.includes(s)));
In other words: Filter my array objs, on the property storage to keep only those that they dont include any of the strings in search.
I have an array like below:
[
'author/2020/01/01/all_authors_000.csv',
'book/2020/01/01/all_books_000.csv',
'book/2020/01/01/all_books_001.csv',
'book/2020/01/01/all_books_002.csv',
'others/2020/01/01/other_stuff.csv',
]
As you can see there are three items that start with the word book. I want to remove all but one, so I end up with something like:
[
'author/2020/01/01/all_authors_000.csv',
'book/2020/01/01/all_books_000.csv',
'others/2020/01/01/other_stuff.csv',
]
How can I achieve this?
Here is working example:
var array = [
"author/2020/01/01/all_authors_000.csv",
"book/2020/01/01/all_books_000.csv",
"book/2020/01/01/all_books_001.csv",
"book/2020/01/01/all_books_002.csv",
"others/2020/01/01/other_stuff.csv",
];
var filteredArray = [];
var previous = "";
for (let i of array) {
if (i.substr(0, i.indexOf("/")) != previous) {
filteredArray.push(i);
previous = i.substr(0, i.indexOf("/"));
}
}
Every loop the value before "/2020" is stored inside the previous variable, and the if statement checks, if the value is the same as in the previous loop. If not, it pushes it into the filteredArray.
Therefore filteredArray is the array without duplicates.
Here is another method of doing it. Basically a function that takes in your array and a criteria to identify duplicates (in your case book). All of these duplicates will be removed but the first one.
const array = [
"author/2020/01/01/all_authors_000.csv",
"book/2020/01/01/all_books_000.csv",
"book/2020/01/01/all_books_001.csv",
"book/2020/01/01/all_books_002.csv",
"others/2020/01/01/other_stuff.csv",
];
const removeDuplicates = (array, criteria) => {
return array.filter(
(path) =>
![...array.filter((path) => path.includes(criteria)).splice(1)].includes(
path
)
);
};
console.log(removeDuplicates(array, "book"));
Say I have an object like so...
and I have an array with ids like this..
array = ['21d32fwef23fw32f3', '21we3weasdf23rfwfwf3']
how can I return only the objects that have sys.ids that match the ids in the array
Ive tried using lodash like so..
getWeekItems(weekNumber) {
this.contenfulService.getWeekItems(weekNumber)
.then((weekOverview) => {
this.weekOverviewCompleted = _.filter(weekOverview, this.completedIds);
console.log(this.weekOverviewCompleted);
}).then(() => console.log(this.weekOverview));
}
but Im getting an empty array back??
is there a better way to do this??
This is how you can get the filtered result :
_.filter(weekOverview, (item) => {
return this.completedIds.indexOf(item.sys.id) > -1 ;
});
// OR Simple javascript filter function
weekOverview.filter(item => {
return this.completedIds.indexOf(item.sys.id) > -1 ;
})
JS function 'filter' does not work on mobile devices. Use the same function defined in Lodash library.