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];
Related
I would like some assistance to remove duplicates and remove the | and the '' at the start and end.
My code so far
const thedates = this.results
.filter((result) => result.thedate)
.map((item) => item.thedate)
.filter((thedate, i, arr) => arr.indexOf(thedate) === i);
// Split multiple thedates in strings and store in an array
let thedate = [];
thedates.forEach((item) => {
const splitArr = item.split(", ");
thedate = thedate.concat(splitArr).sort();
});
// Filter again for unique thedates
this.thedates = thedate.filter(
(thedate, i, arr) => arr.indexOf(thedate) === i
);
My output in the console from the code above
'full-time', 'full-time|full-time', 'full-time|full-time|full-time', 'full-time|full-time|full-time|full-time', 'full-time|full-time|part-time|full-time|part-time|part-time',
I would just like each entry to say: full-time, part-time or full-time if there is just one between the quotes.
Can anyone help to add to my code please?
You're essentially asking two things, how to turn a delimited string into array and how to remove duplicate values from an array. You can parse by using the .split() method, and remove duplicates from an array by constructing a set with it then turning it back into an array with the spread operator.
Altogether (where array is your input array):
let filteredArray = [ ...new Set( string.split( '|') ) ]
const string = "full-time|part-time|full-time|part-time|full-time|part-time|full-time|part-time|full-time|part-time|full-time|part-time|part-time|full-time|full-time|part-time|full-time|part-time|full-time|full-time|part-time|part-time";
let filteredArray = [ ...new Set( string.split( '|') ) ]
let result = filteredArray.join(', ');
console.log(result)
You could try something like this (similar to #Julien Mellon's post) where you use .split(), but you return an array of arrays with the second level array being the entry:
const thedates = ['full-time', 'full-time|part-time', 'full-time|part-time|full-time', 'full-time|full-time|part-time|full-time', 'full-time|full-time|part-time|full-time|part-time|part-time']
const theDatesFormatted = thedates.map(item => {
const arr = item.split('|')
const uniqueArr = [...new Set(arr)]
return uniqueArr
})
console.log(theDatesFormatted)
if your inputs are
'full-time', 'full-time|full-time', 'full-time|full-time|full-time', 'full-time|full-time|full-time|full-time', 'full-time|full-time|part-time|full-time|part-time|part-time'
perhaps you could just call .split('|') ?
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);
I am expecting permutation array to be as below
but the result i am getting on executing the code in the snippet is not what i want.
can someone explain me, why isnt the output as i expected.
permutation [[ "a","b","a"],["b","a","a"],["a","a","b"]]
function permAlone(str) {
const createPermutation = () => {
let arr = Array.from(str);
let permutation = [];
Array.from(str).forEach(_ele => {
const first = arr.shift();
arr = arr.concat(first);
permutation.push(arr)
});
console.log('permutation',permutation);
};
createPermutation();
return str;
}
permAlone("aab");
When you push arr to permutation it keeps a reference, when you modify arr on the subsequent iterations you modify it affects the content of the permutation array, a simple way force a copy of an array is using the method slice.
function permAlone(str) {
const createPermutation = () => {
let arr = Array.from(str);
let permutation = [];
Array.from(str).forEach(_ele => {
const first = arr.shift();
arr = arr.concat(first);
permutation.push(arr.slice())
});
console.log('permutation',permutation);
};
createPermutation();
return str;
}
permAlone("aab");
clarification
In response to your comment I am crating a simpler example.
const arr1 = []
const arr = []
arr.push(1)
arr1.push(arr)
console.log(arr1) // here you se what you would expect
arr.push(2) // arr1 has a reference to this object
console.log(arr1) // here you see that arr1 changed
If you push a slice this will add a copy of arr, instead of a reference to it
const arr1 = []
const arr = []
arr.push(1)
arr1.push(arr.slice()) // what is added is a copy of arr
console.log(arr1) // here you se what you would expect
arr.push(2) // arr1 does not have a reference to this object
console.log(arr1) // here you see that arr1 is not changed
The problem in your code was you were pushing deep copy of your arr array. Instead of that you should do shallow copy with using slice() method. When you deep copy the array it passes its address which changes its value after its last iteration instead of that you should pass array's value using slice method so that your code will work fine.
function permAlone(str) {
const createPermutation = () => {
let arr = Array.from(str);
let permutation = [];
Array.from(str).forEach(_ele => {
const first = arr.shift();
arr = arr.concat(first);
permutation.push(arr.slice())
});
console.log('permutation',permutation);
};
createPermutation();
return str;
}
permAlone("aab");
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);
I have a multidimentional array:
(3) [Array(1), Array(1), Array(1)]
0:["('idDocDetail','0','$createdBy')"]
1:["('idDocDetail','2','$createdBy'),('idDocDetail','4','$createdBy')"]
2:["('idDocDetail','0','$createdBy')"]
I need to replace the string value idDocDetail with the index number, like this.
(3) [Array(1), Array(1), Array(1)]
0:["('0','0','$createdBy')"]
1:["('1','2','$createdBy'),('1','4','$createdBy')"]
2:["('2','0','$createdBy')"]
I'm trying to use replace, but I got the replace is not a function error.
array.forEach(function(item, index) {
return item.toString().replace('idDocDetail', index);
});
what am I doing wrong? Replace is the right way to do this?
I do recommend you to learn to perform changes in immutable manner. This is where Array.prototype.map plays well
const data = [
["('idDocDetail','0','$createdBy')"],
["('idDocDetail','2','$createdBy'),('idDocDetail','4','$createdBy')"],
["('idDocDetail','0','$createdBy')"]
]
const modified = data.map((item, index) =>
item.map(str => str.replace(/idDocDetail/g, index ))
)
modified.forEach(x => console.log(JSON.stringify(x)))
Here, this works for your code structure. It uses map() to produce a new array by just replacing the string of interest with the index.
EDIT: Added a nested map for clarity + regular expression to find all instances of 'idDocDetail' in the string, not just the first one. replace method when given a raw string value only handles the first instance of a string occurring.
const array = [["('idDocDetail','0','$createdBy')"],
["('idDocDetail','2','$createdBy'),('idDocDetail','4','$createdBy')"],
["('idDocDetail','0','$createdBy')"]]
var find = 'idDocDetail';
var re = new RegExp(find, 'g');
let newArray = array.map((val, i) => val.map(string => {
return string.replace(re, i)
}))
console.log(newArray)
You can loop over your array and edit it.
let array = [
["('idDocDetail','0','$createdBy')"],
["('idDocDetail','2','$createdBy'),('idDocDetail','4','$createdBy')"],
["('idDocDetail','0','$createdBy')"],
];
array.forEach((e, i) => {
array[i] = [e[0].replace(/idDocDetail/g, i)];
});
console.log(array);
You can not replace an item by calling a method on the item being replaced. Instead you need to call it on the array. You can do it this way:
for (var i=0; i<array.length; i++) {
array[i][0] = i;
}
forEach ignores the return of the callback. You need to assign to the original array at the current index.
var array = [
["('idDocDetail','0','$createdBy')"],
["('idDocDetail','2','$createdBy'),('idDocDetail','4','$createdBy')"],
["('idDocDetail','0','$createdBy')"]
];
array.forEach(function(item, index) {
array[index] = item.map(s => s.replace('idDocDetail', index));
});
console.log(array);