I am trying to implement lodash _.difference(array, [values]) using .filter() method - lodash

The method/function needs to return an array that has elements in the 1st array that are not present in the second array.
like,
var arr1 = [1,2,3];
var arr2 = [2,3,4,5,6];
should return [1];
and I need to do this using .filter() method!

You can use Array.filter() with Array.includes():
const arr1 = [1,2,3];
const arr2 = [2,3,4,5,6];
const difference = (a, b) => a.filter(item => !b.includes(item));
const result = difference(arr1, arr2);
console.log(result);

Related

for loop only iterating twice with axios

const [Datalist,setDatalist] = useState([]);
useEffect(() => {
axios.get( 'http://0.0.0.0:8000/api/v1/questions/history/1')
.then(response => {
const questions = response.data;
const datalist = [];
for (let i = 0; i < questions.length - 1; i++) {
const data = new Object();
data.isExpanded = false;
data.question_id = questions[i].id;
data.question = questions[i].content;
data.type = questions[i].type;
data.commentType = questions[i].comment_type;
data.answer = [];
datalist.push(data);
}
setDatalist(datalist);
});
},[]);
I have three questions in my database currently. The for loop should be iterating through 0 to 2, however, it is only iterating twice.
And I'm also having problems putting the data into Datalist.
Anybody know where the issue is??
Thanks in advance!!
Change your for loop to this:
for (let i = 0; i < questions.length; i++)
Since you are iterating over each question you receive, you could use the map-method (if your environment supports ES6-Syntax - but since you're using react, it most likely dooes).
From the MDN Docs:
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
With map, your code could look like this:
(Also note the removal of const data = new Object();. you can initialize an object and assign its properties/values at the same time)
const [Datalist,setDatalist] = useState([]);
useEffect(() => {
axios.get( 'http://0.0.0.0:8000/api/v1/questions/history/1')
.then(response => {
const questions = response.data;
const datalist = questions.map(question => {
return {
isExpanded: false;
question_id: question.id;
question: question.content;
type: question.type;
commentType: question.comment_type;
answer: [];
};
});
setDatalist(datalist);
});
},[]);

component status is not updated vue-js

im new in vuejs, i have a component which is a custom table that receives a props,this is an array with all the data in order that table consume and show the data. The main problem is that i got the logic to sort the field in the asc/desc table therefore when i click in one of the header the table invoke the next method
order(columnIndex: number) {
const thisRef = this
const arr = this.currentOrder;
let sortedArray = this.rows
.map((row, rowNumber) => ({
row: row,
rowNumber: rowNumber
}))
.sort((a, b): number => {
const cellNumberA =
thisRef.subcolumnsLabels.length * a.rowNumber + columnIndex
const cellNumberB =
thisRef.subcolumnsLabels.length * b.rowNumber + columnIndex
const cellValueA = thisRef.getCellValue(cellNumberA)
const cellValueB = thisRef.getCellValue(cellNumberB)
return cellValueA - cellValueB
if(arr[columnIndex]){
arr[columnIndex] = false;
return cellValueB - cellValueA
}else{
arr[columnIndex] = true;
}
}).map((rowWithRowNumber) => rowWithRowNumber.row)
this.$store.dispatch('market/setSiData',sortedArray)
},
This method receives one columnIndex this is the number of column in which has been click, the same one is worth for ask the position of the array and check if is true or false.
data() {
return {
columsOrder: [false,false,false,false,false,false,false],
}
},
The problem is a few times this works, change for true and sometimes no, i have no idea why that is happen. Any thoughts ?
Please read Change Detection Caveats - For Arrays:
Vue cannot detect the following changes to an array:
When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue
When you modify the length of the array, e.g. vm.items.length = newLength
You are doing (1) here:
arr[columnIndex] = false
You should use this.$set instead:
this.$set(arr, columnIndex, false)

custom sum elements by key using lodash

I do have two objects containing keys like
var a = {bar:[1,2], foo:[7,9]}
var b = {bar:[2,2], foo:[3,1]}
I want to get the fallowing results:
var c = {bar:[3,4], foo:[10,10]}
I already have a for logic like:
for (let key in b) {
if (a[key]) {
a[key][0] += b[key][0];
a[key][1] += b[key][1];
}
else a[key] = b[key];
}
But I would like to make this logic in a lodash way. How can I Do it?
You can use create a function that takes n objects, and collects them to an array using rest parameters. Now you can spread the array into _.mergeWith() to combine the objects, and in the customizer function sum the items in the arrays using Array.map() or lodash's _.map() and _.add():
const { mergeWith, isArray, map, add } = _
const fn = (...rest) => _.mergeWith({}, ...rest, (o = [], s) =>
map(s, (n, i) => add(n, o[i]))
)
const a = {bar:[1,2], foo:[7,9]}
const b = {bar:[2,2], foo:[3,1]}
const c = {bar:[3,2], foo:[5,6]}
const d = {bar:[4,2], foo:[5,4]}
const result = fn(a, b, c, d)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
You can also use lodash/fp to create a function that merges all values to a multidimensional array with _.mergeAllWith(), then transpose the arrays using _.zipAll(), and sums each array:
const { rest, flow, mergeAllWith, isArray, head, mapValues, zipAll, map, sum } = _
const fn = rest(flow(
mergeAllWith((o, s) => [...isArray(head(o)) ? o : [o], s]), // combine to a multidimensional array
mapValues(flow(
zipAll,
map(sum)
)),
))
const a = {bar:[1,2], foo:[7,9]}
const b = {bar:[2,2], foo:[3,1]}
const c = {bar:[3,2], foo:[5,6]}
const d = {bar:[4,2], foo:[5,4]}
const result = fn(a, b, c, d)
console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash#4(lodash.min.js+lodash.fp.min.js)'></script>
You can accomplish this using plain JavaScript with Object.entries, concat and reduce:
const a = { bar: [1,2], foo: [7,9] };
const b = { bar: [2,2], foo: [3,1] };
const entries = Object.entries(a).concat(Object.entries(b));
const result = entries.reduce((accum, [key, val]) => {
accum[key] = accum[key] ? accum[key].map((x, i) => x + val[i]) : val;
return accum;
}, { });
console.log(result);

how to iterate through two arrays simultaneously with lodash

I have
A = [1,2,3,4,5,6,7]
B = [3,5,9]
I want to get an array C containing the last elements < than elements in B, like
C = [2,4,7], by using Lodash
I tried
C=_.map(A, a = (v) -> v == _.findLast(A, b = (v) -> v < _.forEach(B, c = (v) -> v==v)))
which does not work. Above I used coffeescript instead of javascript, but please reply with either, I want a solution using lodash, without explicit looping through B elements, thank you.
The forEach is redundant, and just returns the original collection:
const A = [1,2,3,4,5,6,7]
const B = [3,5,9]
// C = [2,4,7], by using Lodash
const result = _.map(B, n => _.findLast(A, m => m < n));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
I know you said you want a lodash soultion, but just in case you were curious here is a way to get your desired array using vanilla ES6:
const A = [1, 2, 3, 4, 5, 6, 7];
const B = [3, 5, 9];
const C = findEls(A, B);
function findEls(A, B) {
const copy = [...A].reverse(); //Copy since reverse is an in-place operation
return B.map(b => {
return copy.find(a => a < b);
});
}
console.log(C);

How do I apply a map function to a tensor ? (Tensorflow.js)

How can I apply a function to each elements of a tensor like
var new_tensor = old_tensor.map(map_function)
If you use the dataSync method of oldTensor you can get a TypedArray which you can map over.
var old_tensor_vals = old_tensor.dataSync()
var new_tensor_vals = old_tensor_vals.map(map_function)
If your map_function is specific enough, you can do it simply by using tensor math.
The function below is the implementation of:
old => Math.random()>chance?Math.random():old;
const old = tf.randomUniform([10], 0, 10);
const chance = 0.75;
const mapped = tf.tidy(() => {
const max = Math.round(100 * chance);
const min = max - 1;
const random = tf.randomUniform([old.shape[0]], 0, 100).floor();
const ones = random.clipByValue(min, max).sub(tf.scalar(min));
ones.print();
const zeros = ones.sub(tf.scalar(1)).neg();
zeros.print();
const newValues = tf.randomUniform([old.shape[0]]); //or whatever you want
//newValues.print();
return old.mul(ones).add(newValues.mul(zeros));
});
old.print();
mapped.print();
<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs#0.10.0">
</script>