I want to sort array1 using array2.
var array1 = ["cat","dog","mouse","elephant","ant","cow","goat","hen"];
var array2 = ["mouse","cow","goat"];
The result should look like
var another_array = ["mouse","cow","goat", "bird"--- then rest of the values in array1]
Just taken from object with the order the value or Infinity
for the delta.
var array1 = ["cat", "dog", "mouse", "elephant", "ant", "cow", "goat", "hen"], array2 = ["mouse", "cow", "goat"], order = array2.reduce((r, k, i) => (r[k] = i + 1, r), {}); array1.sort((a, b) => (order[a] || Infinity) - (order[b] || Infinity)); console.log(array1);
Sounds like you're looking for concatenation and filtering:
>>> array2.concat(array1.filter(i => !array2.includes(i)))
["mouse", "cow", "goat", "cat", "dog", "elephant", "ant", "hen"]
Something like this - concatenation and a filter
const array1 = ["cat","dog","mouse","elephant","ant","cow","goat","hen"]; const array2 = ["mouse","cow","goat"]; const anotherArray = [...array2, "bird", ...array1.filter(item =>.array2.includes(item))] console.log(anotherArray)
Use concat function
var hege = ["Cecilie", "Lone"]; var stale = ["Emil", "Tobias", "Linus"]; var children = hege.concat(stale); console.log(children)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.