Remove values using condition from multidimensional array using java-script - javascript

I have a multidimensional array as following.
[['Base: Values','55','98','90.8'],['Value First','55','98','90.8'],['Top','55','98','90.8'],['Bottom','55','98','90.8']]
I want to remove entire values if it includes 'Top' or 'Bottom', so that i will get a result like this:
[['Base: Values','55','98','90.8'],['Value First','55','98','90.8']]
Somebody give me a solution please. Thanks in advance.

You can filter the array, providing a function to determine if an element should be included or not :
array.filter(e => !e.includes('Top') && !e.includes('Bottom'));
Example:
const data = [
['Base: Values','55','98','90.8'],
['Value First','55','98','90.8'],
['Top','55','98','90.8'],
['Bottom','55','98','90.8']
]
const filtered = data.filter(e => !e.includes('Top') && !e.includes('Bottom'));
console.log(filtered)
console.log(data)
EDIT: To exclude if any string in array values contains a specific part, you could change the predicate to check if at least one string contains the part:
array.filter(e => !e.some(i => i.includes('part to find')));
Example:
const data = [
['Base: Values','55','98','90.8'],
['Value First','55','98','90.8'],
['Top','55','98','90.8'],
['Bottom','55','98','90.8']
]
const filtered = data.filter(e => !e.some(i => i.includes('Value')));
console.log(filtered)
console.log(data)

Related

how can i check if an array of objects contains a key which is in array of strings js?

We have an array of objects like
const arr = [{id: "someId", name: {...}}, ...];
const skippedKeys = ["id"...]
How can i filtered the array of object based on skipped keys?
The result should be:
const result = [{name: {...}}, ...];
Also i don't want to make a cycle inside the cycle.
the result also could be implemented using lodash library.
we should remove key with value as well.
Since you stated that it could be implemented using lodash, here is some code using lodash:
let result = _.map(arr, (el)=> _.omit(el, skippedKeys))
const result = arr.map(obj =>
Object.keys(obj).reduce(
(res, key) => (
skippedKeys.includes(key) ? res : {...res, [key]: obj[key]}
),
{},
));
It's simple and no need for any nested cycles. There are two option to do that
Using includes function
const result = arr.filter((item) => !result.includes(item.id));
Using set
const dataSet = new Set(skippedKeys);
const result = arr.filter((item) => !dataSet.has(item.id));
I prefer the second one as it excludes double checks. Hope the answer was helpful.

replace and filter method in one condition using JavaScript / node js [duplicate]

This question already has answers here:
Map and filter an array at the same time
(16 answers)
Closed 1 year ago.
I have an array which look like this
["home/work/abc.jpg",
"home/work/fish.pdf",
"home/work/fish.jpg",
"home/work/doc/animal.jpg",
"home/work/doc/animal.pdf"];
so I want to filter array which contain ".jpg" extension file so I filtered it out by using
array= array.filter((data)=>{
return data.indexOf(".jpg")>=0
});
so I got my expected value as
[ "home/work/abc.jpg",
"home/work/fish.jpg",
"home/work/doc/animal.jpg"
]
and I replace "home/work/" by using map function
let rep="home/work/";
array = array.map((data)=>{
data.replace(rep,"")
});
and got my value as
[ "abc.jpg",
"fish.jpg",
"doc/animal.jpg"
]
but the problem is I have to use two method to filter and replace them is there any possibility I can merge this two method and minimise my code
array= array.filter((data)=>{
return data.indexOf(".jpg")>=0
});
let rep="home/work/";
array = array.map((data)=>{
data.replace(rep,"")
});
expected output
[ "abc.jpg",
"fish.jpg",
"doc/animal.jpg"
]
By using any chaining method ?
You can chain off of the filtered array without creating another variable, and by using implicit return to make things more concise:
const filenames = ["home/work/abc.jpg",
"home/work/fish.pdf",
"home/work/fish.jpg",
"home/work/doc/animal.jpg",
"home/work/doc/animal.pdf"];
const rep="home/work/";
const result = filenames
.filter(file => file.includes('.jpg'))
.map(file => file.replace(rep, ''));
console.log(result);
To actually do it in a single iteration, you'd have to give up on the chaining, and use reduce or a standard iteration method.
const filenames = ["home/work/abc.jpg",
"home/work/fish.pdf",
"home/work/fish.jpg",
"home/work/doc/animal.jpg",
"home/work/doc/animal.pdf"];
const rep="home/work/";
const result = [];
for (const file of filenames) {
if (file.includes('.jpg')) result.push(file.replace(rep, ''));
}
console.log(result);
You can obtain same result using the same two method that you've used but inside reduce
const arr = [
"home/work/abc.jpg",
"home/work/fish.pdf",
"home/work/fish.jpg",
"home/work/doc/animal.jpg",
"home/work/doc/animal.pdf",
];
const result = arr.reduce((acc, curr) => {
if (curr.indexOf(".jpg") >= 0) {
acc.push(curr.replace("home/work/", ""));
}
return acc;
}, []);
console.log(result);
Try this. This will return the same output you are looking for.
Using both .map and .filter combined.
let array = array
.filter((data) => data.indexOf(".jpg")>=0)
.map((data) => data.replace("home/work/",""))

Filter array for every 3rd element

I'm having trouble to create an array based on a dataset, I want to filter just some elements of it by choosing one element every 3. Could you help me with this?
This is what I did.
var example = dataset.map(function(d){return d.values
.filter(function(d,i){return (i+1)%3===0;})});
the dataset log: {name:"example1", values: Array(46)}
After applying the new array looks like this. And I'm looking for this [219, 2301, 239.....373]
Thanks
Currently, you're trying to run your filter on every item in the array since you're doing it within an iteration of Array.prototype.map. You should filter the array for every third item first, and then run map on the resulting array to avoid mapping values that will end up being null.
const data = [...]
const dataSet = data
.filter((_, i) => i % 3 === 0)
.map(x => x.value)
You could also do it with a single use of Array.prototype.reduce and doing both filter and map in the same iteration like so:
const data = [...]
const dataSet = data.reduce((acc, curr, i) => {
if (i % 3 === 0) acc.push(curr.value)
return acc
}, [])

Filtering array based on nested property

I have an array of objects which has a nested parameter in it and I want to return only those array elements that pass filter based on that nested parameter which is in turn also an array of objects.
[{q:1,w:2,props:{p:1, messages:[{status:true},{status:false},{status:true}]},
{q:3,w:5,props:{p:2, messages:[{status:false},{status:false},{status:false}]},
{q:7,w:0,props:{p:3, messages:[{status:false},{status:false},{status:true}]}
]
My aim is to filter only those objects that contain at least one message with status true.
In this example I would expect to get an array of two objects
[{q:1,w:2,props:{p:1, messages:[{status:true},{status:false},{status:true}]},
{q:7,w:0,props:{p:3, messages:[{status:false},{status:false},{status:true}]}
]
Thanks for help and advice!
some() will let you check if a condition is true at least once. You can use that to filter: filter
let arr = [{q:1,w:2,props:{p:1, messages:[{status:true},{status:false},{status:true}]}},{q:3,w:5,props:{p:2, messages:[{status:false},{status:false},{status:false}]}},{q:7,w:0,props:{p:3, messages:[{status:false},{status:false},{status:true}]}}]
let filtered = arr.filter(item => item.props.messages.some(m => m.status === true))
console.log(filtered)
Use filter.
var result= items.filter(item =>{
return item.props.messages.some(obj => obj.status === true)
})
I created this Fiddle:
http://jsfiddle.net/81ue32ra/2/
var items = [{q:1,w:2,props:{p:1, messages:[{status:true},{status:false},{status:true}]}},
{q:3,w:5,props:{p:2, messages:[{status:false},{status:false},{status:false}]}},
{q:7,w:0,props:{p:3, messages:[{status:false},{status:false},{status:true}]}}
];
var result = items.filter(item =>{
return item.props.messages.some(obj => obj.status === true)
});
console.log(result);
Just filter the main array and check if some of the messages status property is true.
let data = your array;
data.filter(obj => obj.props.messages.some(message => message.status).length > 0)

Remove last letter from map value

So I'm getting this from backend:
{"Item":{"userEmail":"b","Username":"bUsername","Push":"sdsdsd","Password":"sdsds","Buddy":{"datatype":"SS","contents":{"Drake":"Drake","Ola":"Ola","b":"b","d":"d"}}}}
I use Object.Keys to narrow down the contents to:
Drake,Ola,b,d
Which I then map to give:
[{"id":"Drake"},{"id":"Ola"},{"id":"b"},{"id":"d"}]
Which is then used on my Angular Front-end as .id. I want to remove the last letter from each value i.e leaving Drak,Ol etc. I've tried many ways but have failed, how can I achieve this please so that the id has those values?
EDIT
I also want to now get that value that was cut AND add it such that the end product will be [{"id":"Drak",valueThatWasCut:"e"}]
You could iterate the object's keys and build with the short string a new object.
var data = {"Item":{"userEmail":"b","Username":"bUsername","Push":"sdsdsd","Password":"sdsds","Buddy":{"datatype":"SS","contents":{"Drake":"Drake","Ola":"Ola","b":"b","d":"d"}}}},
ids = Object.keys(data.Item.Buddy.contents).reduce(function (r, k) {
var n = k.slice(0, -1);
return n ? r.concat({ id: n }) : r;
}, []);
console.log(ids);
Perhaps something like :
var arr = [{"id":"Drake"},{"id":"Ola"},{"id":"b"},{"id":"d"}];
var result = arr.map(x => x.id.slice(0,-1));
console.log(result); // [ 'Drak', 'Ol', '', '' ]
Create a temporary contents object and change in that.
Then just set this in the original object. ES6 spread operators would save the rest of data without respecifying all keys and values.
let items = {"Item:{"userEmail":"b","Username":"bUsername","Push":"sdsdsd","Password":"sdsds","Buddy":{"datatype":"SS","contents":{"Drake":"Drake","Ola":"Ola","b":"b","d":"d"}}}};
let contents = items.Item.Buddy.contents;
let contentsNew = Object.keys(contents).map((content) => {
return {[content.substring(0, content.length-1)]: content.substring(0, content.length-1), valueThatWasCut: content[content.length-1]};
});
items = {...items, Item: {...items.Item,Buddy:{...items.Item.Buddy,contents: contentsNew}}};
console.log(items);

Categories