const sort = ["this","is","my","custom","order"]; const myObjects = [ {"id":1,"content":"is"}, {"id":2,"content":"my"}, {"id":3,"content":"this"}, {"id":4,"content":"custom"}, {"id":5,"content":"order"} ];हमें एक JavaScript फ़ंक्शन लिखना है जो ऐसे दो ऐरे लेता है और दूसरे ऑब्जेक्ट्स के ऐरे को पहले ऐरे के आधार पर सॉर्ट करता है ताकि ऑब्जेक्ट्स की content प्रॉपर्टी पहले ऐरे के स्ट्रिंग्स से मेल खाए।
इसलिए, उपरोक्त ऐरे के लिए आउटपुट इस तरह दिखना चाहिए -
const output = [ {"id":3,"content":"this"}, {"id":1,"content":"is"}, {"id":2,"content":"my"}, {"id":4,"content":"custom"}, {"id":5,"content":"order"} ];उदाहरण
इसका कोड होगा -
const arrLiteral = ["this","is","my","custom","order"]; const arrObj = [ {"id":1,"content":"is"}, {"id":2,"content":"my"}, {"id":3,"content":"this"}, {"id":4,"content":"custom"}, {"id":5,"content":"order"} ]; const sortByReference = (arrLiteral, arrObj) => { const sorted = arrLiteral.map(el => { for(let i = 0; i < arrObj.length; ++i){ if(arrObj[i].content === el){ return arrObj[i]; } }; }); return sorted; }; console.log(sortByReference(arrLiteral, arrObj));आउटपुट
कंसोल में आउटपुट होगा -
[ { id: 3, content: 'this' }, { id: 1, content: 'is' }, { id: 2, content: 'my' }, { id: 4, content: 'custom' }, { id: 5, content: 'order' } ]