So I am working in typescript where I need to modify an array to some specific pattern.
Here is my array:
["sunday","monday","tuesday"]
This is what I need it to be like:
["day:Sunday","day:Monday","day:Tuesday"]
I have already tried map method like this:
result = arr.map(x => ({day: x}));
But map gives me result some different which is not needed:
[{"day":"sunday"},{"day":"monday"},{"day":"tuesday"}]
You're trying to prepend the strings and to change the first letter to upper:
const arr = ["sunday","monday","tuesday"];
const result = arr.map(x => 'day:' + x[0].toUpperCase() + x.slice(1));
console.log(result);
The problem is that you are adding those brackets, here's a solution:
const original = ["sunday","monday","tuesday"]
console.log(original)
const result = original.map(day => `day:${day}`);
console.log(result)
//["day:sunday", "day:monday", "day:tuesday"]
Array map is the right method, you just need to return a string, not an object:
result = arr.map(d => `day:${d.toUpperCase()}`)
const days = ["sunday","monday","tuesday"];
const dayFun = days.map((day) => {
const dayUppercase = day.charAt(0).toUpperCase() + day.slice(1);
return `day:${dayUppercase}`;
});
console.log(dayFun);
Related
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.
I am trying to create a javascript version of python's pop function.
Here is what I have so far:
function pop(arr, idx) {
arr = arr.splice(0, idx).concat(arr.splice(idx + 1));
console.log(arr);
}
I am not sure of why it is only returning the first part and not combining with the second.
are you looking for something like this? maybe you can modify it so that the pop function returns the removed element.
const arr1 = [10,20,30,40,50,60];
const arr2 = [10,20,30,40,50,60];
const arr3 = [10,20,30,40,50,60];
function pop(arr, idx) {
removedEl = arr.splice(idx,1)[0];
console.log('removed element: ',removedEl)
console.log('final array: ',arr);
}
pop(arr1,0);
pop(arr2,2);
pop(arr3,5)
Array.splice() modifies the array. It doesn't create a new array. All you need is this:
const pythonPop = ( arr , i = -1 ) => arr.splice(i,1)[0];
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/",""))
I have sample JSON in form of
var sample=[{"id":200,"children":[{"value":300,"type":"SINGLE"},{"value":400,"type":"CLASSIC"},{"value":600,"type":"DUAL"}]},{"id":300,"children":[{"value":500,"type":"TRIO"},{"value":600,"type":"MUSICAL"},{"value":700,"type":"UMBRELA"}]}]
var result = [];
sample.forEach(function(e){
let obj = {}
obj.id=e.id
obj['somekey']=e.children[0].value
obj['someanotherkey']=e.children[1].type
result.push(obj);
})
console.log(result)
How do i can achieve same using map es-6
var sample=[{"id":200,"children":[{"value":300,"type":"SINGLE"},{"value":400,"type":"CLASSIC"},{"value":600,"type":"DUAL"}]},{"id":300,"children":[{"value":500,"type":"TRIO"},{"value":600,"type":"MUSICAL"},{"value":700,"type":"UMBRELA"}]}]
var output = sample.map(({ id, children }) => ({ id, ...children[0] }));
console.log(output);
.map() returns an array, so you must set up a variable to hold that result. Then, within the loop, you use return to effectively push items into the array.
var sample=[{"id":200,"children":[{"value":300,"type":"SINGLE"},{"value":400,"type":"CLASSIC"},{"value":600,"type":"DUAL"}]},{"id":300,"children":[{"value":500,"type":"TRIO"},{"value":600,"type":"MUSICAL"},{"value":700,"type":"UMBRELA"}]}];
let result = sample.map(function(e){
let obj = {}
obj.id=e.id;
obj['value']=e.children[0].value;
obj['type']=e.children[0].type
return obj;
});
console.log(result);
If you want to be able to chose the children index:
const getDataChild = (a, i) => a.map(({id, children:ch}) => ({id, ...ch[i]}));
console.log(getDataChild(sample, 0)); // where 0 is the desired index
we have an array like below, length of the array is not constant(may increase/decrease).
[255028AD_ABC_DE_2057,261830AD_ABC_FG_2876,.......]
My aim is to achieve only the first part of each index like below.
[255028AD,261830AD,.........]
Please help.
Try this:
var arr = ['255028AD_ABC_DE_2057', '261830AD_ABC_FG_2876'];
arr = arr.map(el => el.split('_')[0]);
console.log(arr);
With Array.map() and String.substr() functions:
var arr = ['255028AD_ABC_DE_2057', '261830AD_ABC_FG_2876' ],
result = arr.map(v => v.substr(0, v.indexOf('_')));
console.log(result);
v.indexOf('_') - to find the 1st position of _ char
v.substr(0, v.indexOf('_')) - extracting the substring starting from the position 0 to the 1st position of _ char (getting slice)
You could match the first non underscore characters and return the first item of the matching result.
var array = ['255028AD_ABC_DE_2057', '261830AD_ABC_FG_2876'],
result = array.map(s => s.match(/^[^_]+/)[0]);
console.log(result);
Something like that should work:
const arr = ['255028AD_ABC_DE_2057','261830AD_ABC_FG_2876'];
const arrModified = arr.map(element =>
element.substr(0, element.indexOf('_')));
console.log(arrModified)
Use Array.map function so your code will look something like this
[].map(item => item.split('_')[0])
where [] is your array
in ES5 syntax it will look like
[].map(function(item) {
return item.split('_')[0];
})
Hope that helps
Just use map https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/map
with
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/split
like
var array = ["12_bla","13_ble"].map(function (el) { return el.split('_',1)[0]; });
Using a for ... of:
var arr = ['255028AD_ABC_DE_2057', '261830AD_ABC_FG_2876'];
var index = 0;
for (item of arr) {
arr[index] = item.split('_')[0];
index++;
}
console.log(arr);
You may also do like
var result = ["255028AD_ABC_DE_2057","261830AD_ABC_FG_2876"].map(s => s.replace(/_.*/,""));
console.log(result);