Is there any way i can filter files with given extension and then further filter them
for eg: I have .txt extension and i want to get all my .txt from an array
file=
[ "animal_bio.txt",
"xray.pdf",
"fish_bio.txt",
"mammal_doc.txt",
"human_bio.txt",
"machine.jpg"
]
filtered output contain all .txt extension and further it should contain all the files which have _bio.txt name in it.
so output look like
futherFile=
[ "human_bio.txt",
"fish_bio.txt",
"animal_bio.txt"
]
You can use String.protytype.endsWith function to compare the strings with your extension
const file =
[ "animal_bio.txt",
"xray.pdf",
"fish_bio.txt",
"mammal_doc.txt",
"human_bio.txt",
"machine.jpg"
]
result = file.filter((fileName) => fileName.endsWith("_bio.txt"));
console.log(result)
You can use the Array.filter method and use the String.endsWith method to filter. An example -
// List of files
file = ["animal_bio.txt",
"xray.pdf",
"fish_bio.txt",
"mammal_doc.txt",
"human_bio.txt",
"machine.jpg"
]
// Filtering by extension
file.filter(x => x.endsWith(".txt"));
Hope it helped :)
You can easily achieve this result using reduce and match
When matching for the doc or bio, You can even restrict more to get the string only if _doc.txt is at end of the string using Regular expression /_bio.txt$/
const arr = [
{
id: "1",
name: "animal_bio.txt",
},
{
id: "2",
name: "xray.pdf",
},
{
id: "3",
name: "animal_doc.txt",
},
{
id: "4",
name: "fish_doc.txt",
},
{
id: "5",
name: "flower_petals.jpg",
},
{
id: "5",
name: "plant_roots.jpg",
},
{
id: "6",
name: "human_image.jpg",
},
{
id: "7",
name: "human_bio.txt",
},
{
id: "8",
name: "mammal_doc.txt",
},
];
const result = arr.reduce((acc, { name }) => {
if (name.match(/\.txt$/)) {
if (name.match(/_bio/)) {
acc[0].push(name);
} else {
acc[1].push(name);
}
}
return acc;
},
[[], []]
);
console.log(result);
Then you can get the element containing doc and bio using array destructuring as
const [bioArr, docArr] = result;
console.log(bioArr);
console.log(docArr);
const arr = [
{
id: "1",
name: "animal_bio.txt",
},
{
id: "2",
name: "xray.pdf",
},
{
id: "3",
name: "animal_doc.txt",
},
{
id: "4",
name: "fish_doc.txt",
},
{
id: "5",
name: "flower_petals.jpg",
},
{
id: "5",
name: "plant_roots.jpg",
},
{
id: "6",
name: "human_image.jpg",
},
{
id: "7",
name: "human_bio.txt",
},
{
id: "8",
name: "mammal_doc.txt",
},
];
const result = arr.reduce(
(acc, { name }) => {
if (name.match(/\.txt$/)) {
if (name.match(/_bio/)) {
acc[0].push(name);
} else {
acc[1].push(name);
}
}
return acc;
},
[[], []]
);
const [bioArr, docArr] = result;
console.log(bioArr);
console.log(docArr);
you can use filter function from ES6 like:
const txtFile = file.filter((item) => (item.split('_'))[1] === 'bio.txt')
Related
I have an array of objects, each array has a key of name and then another array of objects:
const myArray = [ { name: "1", item: [{}] }, { name: "2", item: [{}] }, { name: "1", item: [{}] } ]
Now for example sometimes that name key will be the same, i want to be able to check if that name exists and if it does exist push the item into that array object and not into a new object.
The behaviour im getting is above but i would like:
const myArray = [ { name: "1", item: [{ item1, item2 etc }] }, { name: "2", item: [{}] }, { name: "3", item: [{}] } ]
Thanks so much in advance!
You can get the desired result using Array.reduce(), grouping by name.
If two objects in myArray share the same name, the item values are combined.
const myArray = [ { name: "1", item: [{ id: 1 }] }, { name: "2", item: [{ id: 2}] }, { name: "1", item: [{ id: 3}] } ]
const result = Object.values(myArray.reduce((acc, { name, item }) => {
acc[name] = acc[name] || { name, item: [] };
acc[name].item.push(...item);
return acc;
}, {}))
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }
Here's a solution using Array.prototype.reduce function.
const myArray = [ { name: "1", item: [{}] }, { name: "2", item: [{}] }, { name: "1", item: [{}] } ];
const output = myArray.reduce((acc, curr) => {
const index = acc.findIndex(pre => pre.name === curr.name);
if(index !== -1) {
acc[index].item = acc[index].item.concat(curr.item);
} else {
acc.push(curr);
}
return acc;
}, []);
console.log(output);
i am trying to find a list of synced users between two arrays (objArray1 & objArray2) and return the data from objArray1 along with 'aid' in Objarray2. I have the below code working, but i am trying to see if can return 'aid' from objArray2 as well in the below format.
Code sample below
// SystemA
const objArray1 = [
{ id: "1", name: "John" },
{ id: "2", name: "Jack" },
{ id: "3", name: "Sam" },
{ id: "4", name: "Bill" },
];
// SystemB
const objArray2 = [
{ id: "1", name: "John", aid:"uuud2905555" },
{ id: "3", name: "Sam" }, aid:"uuud29029303"
{ id: "5", name: "Bob" }, aid:"uuud29435454"
];
const array1IDs = objArray1.map((item) => {
return item.id
})
// Result: array1IDs = ["1", "2", "3", "4"];
const array2IDs = objArray2.map((item) => {
return item.id
})
// Result: array2IDs = ["1", "3", "5"];
// FIND SYNCED USERS
// Compare the id value of each item in objArray1 with each item of objArray2
// Return the ones that match.
const syncedUsers = objArray1.filter((item) => {
const found = objArray2.find((element) => element.id === item.id);
return found;
});
Required JSON Format, please note that all matching items should be returned from objArray1, with the exception of 'aid' from objArray2
{
"records": [
{
"id": {aid}, // from objArray2
"fields": {
"Name":{name}, // from objArray1
"sid": {id} // from objArray1
}
]
}
Presented below is one possible way to achieve the desired objective.
Code Snippet
// method to create result as "JSON"
const createJSON = (arr1, arr2) => (
// use "stringify" to transform JavaScript object into JSON
JSON.stringify({
// set-up the "records" prop
records: arr2
.filter( // filter to keep only those that have matching "id"
({ id }) => arr1.some(ob => ob.id === id)
)
.map( // de-structure & rename props to match desired objective
({ id : sid, name : Name, aid: id }) => ({
id,
fields: {Name, sid}
})
)
})
);
// SystemA
const objArray1 = [
{ id: "1", name: "John" },
{ id: "2", name: "Jack" },
{ id: "3", name: "Sam" },
{ id: "4", name: "Bill" },
];
// SystemB
const objArray2 = [
{ id: "1", name: "John", aid:"uuud2905555" },
{ id: "3", name: "Sam", aid:"uuud29029303" },
{ id: "5", name: "Bob", aid:"uuud29435454" },
];
console.log('result as a JSON: ', createJSON(objArray1, objArray2));
.as-console-wrapper { max-height: 100% !important; top: 0 }
Explanation
Inline comments added to the snippet above.
EDIT
Use name and id from array-1. Used restOfArr1Props to account for all other props of array-1 objects to be included.
const createJSON = (arr1, arr2) => (
JSON.stringify({
records: arr1
.filter(
({ id }) => arr2.some(ob => ob.id === id)
)
.map(
({ id : sid, name : Name, ...restOfArr1Props }) => ({
id: arr2.find(a2 => a2.id === sid)?.aid ?? 'missing aid',
fields: {
Name, sid, ...restOfArr1Props
},
})
)
})
);
// SystemA
const objArray1 = [
{ id: "1", name: "John", prop1: 'value11', prop2: 'value12' },
{ id: "2", name: "Jack", prop1: 'value21', prop2: 'value22' },
{ id: "3", name: "Sam", prop1: 'value31', prop2: 'value32' },
{ id: "4", name: "Bill", prop1: 'value41', prop2: 'value42' },
];
// SystemB
const objArray2 = [
{ id: "1", name: "John", aid:"uuud2905555" },
{ id: "3", name: "Sam", aid:"uuud29029303" },
{ id: "5", name: "Bob", aid:"uuud29435454" },
];
console.log('result as a JSON: ', createJSON(objArray1, objArray2));
.as-console-wrapper { max-height: 100% !important; top: 0 }
const objArray1 = [
{ id: '1', name: 'John', type: 'bully' },
{ id: '2', name: 'Jack', type: 'sporty' },
{ id: '3', name: 'Sam', type: 'kind' },
{ id: '4', name: 'Bill', type: 'poliet' },
];
const objArray2 = [
{ id: '1', name: 'John', aid: 'uuud2905555' },
{ id: '3', name: 'Sam', aid: 'uuud29029303' },
{ id: '5', name: 'Bob', aid: 'uuud29435454' },
];
const syncedUsers = { records: [] };
for (let user1 of objArray1) {
const foundUser = objArray2.find(user2 => user2.id === user1.id);
if (foundUser) {
syncedUsers.records.push({
id: foundUser.aid,
fields: { sid: user1.id, name: user1.name, ...user1 },
});
}
}
console.log(JSON.stringify(syncedUsers));
The code that I have does result in the desired output. However, in my opinion, using these nested for loops is a little ugly and I am trying to refactor my work.
My question is: do you have any suggestions on refactoring the code so that I can avoid the need of using these nested for loops?
I want to loop over a nested object and end up with a result of all unique keys, and an array of all values for that unique key.
{"ABC":["1","100","6"],"DEF":["10","2","5"],"GHI":["14","9"],"HGI":["4"]}
const data = {
something: [
{
innerSomething: {
list: [
{
title: "ABC",
amount: "1"
},
{
title: "DEF",
amount: "10"
},
{
title: "GHI",
amount: "14"
}
],
}
},
{
innerSomething: {
list: [
{
title: "ABC",
amount: "100"
},
{
title: "DEF",
amount: "2"
},
{
title: "GHI",
amount: "9"
}
],
}
},
{
innerSomething: {
list: [
{
title: "ABC",
amount: "6"
},
{
title: "DEF",
amount: "5"
},
{
title: "HGI",
amount: "4"
}
],
}
}
]
};
const results = {};
data.something.forEach((item) => {
item.innerSomething.list.forEach((list) => {
if (results[list.title]) {
// exists already, just push the amount
results[list.title].push(list.amount)
} else {
// Is unique so far, add it to the object
results[list.title] = [list.amount];
}
})
});
console.log(`results: ${JSON.stringify(results)}`);
// These results are the correct and desired output
// {"ABC":["1","100","6"],"DEF":["10","2","5"],"GHI":["14","9"],"HGI":["4"]}
Your implementation is ok, tbh.
The only thing I can suggest differently is to make use of the neat destructuring patterns and spread syntax, considering that the structure of your input object is very well known:
data.something.forEach(({ innerSomething: { list } }) =>
list.forEach(({ title, amount }) =>
results[title] = [...results[title] || [], amount]))
For what it's worth, here is how I'd write it.
const data = {
something: [
{
innerSomething: {
list: [
{
title: "ABC",
amount: "1"
},
{
title: "DEF",
amount: "10"
},
{
title: "GHI",
amount: "14"
}
],
}
},
{
innerSomething: {
list: [
{
title: "ABC",
amount: "100"
},
{
title: "DEF",
amount: "2"
},
{
title: "GHI",
amount: "9"
}
],
}
},
{
innerSomething: {
list: [
{
title: "ABC",
amount: "6"
},
{
title: "DEF",
amount: "5"
},
{
title: "GHI",
amount: "4"
}
],
}
}
]
};
const results = {};
for (let something of data.something) {
for (let item of something.innerSomething.list) {
const { title, amount } = item;
results[title] = results[title] || [];
results[title].push(amount);
}
}
console.log(`results: ${JSON.stringify(results)}`);
Is there any way i can filter values which are present inside Object
[
{
id: "1",
name:"animal_image.jpg"
},
{
id: "2",
name:"fish_image.jpg"
},
{
id: "3",
name:"animal_doc.txt"
},{
id: "4",
name:"fish_doc.txt"
},
{
id: "4",
name:"flower_petals.jpg"
},
{
id: "5",
name:"plant_roots.jpg"
},
{
id: "6",
name:"human_image.jpg"
},
]
i want to filter all the name which contain_image.jpg so output look like this
output=
[ "human_image.jpg",
"anima_image.jpg",
"fish_image.jpg"
]
In this code snippet filtredData is an array of objects where the name includes _image.jpg and output is just an array of names containing _image.jpg
const data = [
{
id: "1",
name: "animal_image.jpg"
},
{
id: "2",
name: "fish_image.jpg"
},
{
id: "3",
name: "animal_doc.txt"
}, {
id: "4",
name: "fish_doc.txt"
},
{
id: "4",
name: "flower_petals.jpg"
},
{
id: "5",
name: "plant_roots.jpg"
},
{
id: "6",
name: "human_image.jpg"
},
]
const filtredData = data.filter(el => el.name.includes("_image.jpg"));
console.log(filtredData);
const output = filtredData.map(el => el.name);
console.log(output);
filter & map
const output = arr
.filter(x => x.name.endsWith('_image.jpg'))
.map(x => x.name);
This question already has answers here:
Remove duplicates form an array
(17 answers)
Closed 5 years ago.
I have this array?
var arr = [{id:"1",Name:"Tom"},
{id:"2",Name:"Jon"},
{id:"3",Name:"Tom"},
{id:"4",Name:"Jack"}]
From array above I need to fecth all existing Names distinct.
var result = getNamesDistinct(arr);
The result should contain result is:
["Tom","Jon","Jack"];
My question is how to get all existing Names from arr distinct?
If Set is available, you can simply do
new Set(arr.map(obj => obj.Name))
(pass the set to Array.from if you need an array)
You can do it via Set object
const arr = [
{ id: "1", Name: "Tom" },
{ id: "2", Name: "Jon" },
{ id: "3", Name: "Tom" },
{ id: "4", Name: "Jack" }
];
const uniqueNames = [...new Set(arr.map(item => item.Name))];
console.log(uniqueNames);
Or you can iterate over the array and add condition to get only unique names.
const arr = [
{ id: "1", Name: "Tom" },
{ id: "2", Name: "Jon" },
{ id: "3", Name: "Tom" },
{ id: "4", Name: "Jack" }
];
const uniqueNames = arr.reduce(function(arr, item) {
if(arr.indexOf(item.Name) === -1) {
arr.push(item.Name);
}
return arr;
}, []);
console.log(uniqueNames);
you can try this
var array = [{
id: "1",
Name: "Tom"
}, {
id: "2",
Name: "Jon"
}, {
id: "3",
Name: "Tom"
}, {
id: "4",
Name: "Jack"
}]
function uniqueNames(array) {
var newArray = [];
array.forEach((value, key) => {
newArray.push(value.Name)
});
return newArray
}
var myNewArray = uniqueNames(array)