'When looping through an array I wish to push the elements to a new array. That array however remains empty
When I run this loop it takes in an array which contains eight numbers, it loops through and simply pushes them to a global array which is named results. For some reason when I console.log this array outside of the loop it returns 0 []. I wish it to return the eight numbers from the other array.
const results = []
const validate = arr => {
for(let i = 0; i < arr.length; i++){
results.push(arr[i])
}
}
console.log(results)
Solution 1:[1]
What you have done here is simply define a function that copies the contents of the array that has been passed into it. You need to call the function
validate with the appropriate value.
const results = []
const validate = arr => {
for(let i = 0; i < arr.length; i++){
results.push(arr[i])
}
}
validate([1,2,3,4,5,6,7,8]);
console.log(results);
Solution 2:[2]
That is because you have to run the function validate, now you are just printing results[] which has no items.
validate(arr);
const results = []
const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const validate = arr => {
for (let i = 0; i < arr.length; i++) {
results.push(arr[i])
}
}
validate(arr);
console.log(results);
But if you want to make a copy, you can just use:
const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const results = [...arr];
console.log(results);
Solution 3:[3]
You missed calling the function.
const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const result = [];
arr.map((num) => result.push(num));
console.log(result);
Solution 4:[4]
const results = []
const validate = (arr) => {
console.log(arr)
arr.forEach((value)=>{
results.push(value)
});
}
validate([1,2,3,4,5,6,7,8]);
console.log(results);
Solution 5:[5]
You might use regular expression for this as follows
import pandas as pd
df = pd.DataFrame({"street":["Main Street","Jon Smith Close","The Rovers Avenue"]})
df2 = df.street.str.extract(r"(?P<Beginning>.+)\s(?P<Ending>\S+)")
df = pd.concat([df,df2],axis=1)
print(df)
output
street Beginning Ending
0 Main Street Main Street
1 Jon Smith Close Jon Smith Close
2 The Rovers Avenue The Rovers Avenue
Explanation: I used named capturing group which result in pandas.DataFrame with such named columns, which I then concat with original df with axis=1. In pattern I used group are sheared by single whitespace (\s), in group Beginning any character is allowed in group Ending only non-whitespace (\S) characters are allowed.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | John S John |
| Solution 2 | |
| Solution 3 | Aniket Kudale |
| Solution 4 | Boringcoder |
| Solution 5 | Daweo |
